안드로이드 자바

[JAVA][Android] UTC 협정 세계시

teamnova 2022. 6. 16. 10:00
728x90

서비스를 만들 때, 시간 표기 방식에 대하여 고민할 때가 많습니다.
예를 들어, 한국 시간을 기준으로 게시글을 작성했을 때,
미국 뉴욕에 있는 유저들은 현지 시간과 다르게 표기됩니다.
이 문제점을 해결하기 위해서 "UTC(협정 세계시)"를 사용합니다.

 

public static String getUTC() throws Exception {
    String utcTime = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date now = new Date();
    String DBDate = sdf.format(now);
    TimeZone tz = TimeZone.getDefault();
    try {
        Date parseDate = sdf.parse(DBDate);
        long milliseconds = parseDate.getTime();
        int offset = tz.getOffset(milliseconds);
        utcTime = sdf.format(milliseconds - offset);
        utcTime = utcTime.replace("+0000", "");
    } catch (Exception e) {
        e.printStackTrace(); throw new Exception(e);
    }
    //System.out.println("협정시: " + utcTime);
    return utcTime;
}

위의 코드는 현재 UTC 시간을 구하는 코드입니다.