[Java] ZonedDateTime, OffsetDateTime , ZoneId, ZoneOffset 클래스

Yujeong·2024년 6월 3일
0

Java

목록 보기
14/22
post-thumbnail

ZonedDateTime이란?

ZonedDateTimeLocalDateTime과 시간대를 모두 표현한다.
ZonedDateTime을 이해하기 위해 ZoneIdZoneOffset 클래스를 먼저 이해할 필요가 있다.

타임존 목록

타임존 안에는 일광 절약 시간제(DST: 썸머 타임)에 대한 정보와 오프셋 정보를 모두 포함한다.

타임존 ID오프셋
UTCUTC+00:00
Europe/LondonUTC+00:00 (DST: UTC+01:00)
Europe/ParisUTC+01:00 (DST: UTC+02:00)
Europe/MoscowUTC+03:00
Asia/SeoulUTC+09:00
Asia/TokyoUTC+09:00
Asia/ShanghaiUTC+08:00
Asia/KolkataUTC+05:30
Australia/SydneyUTC+10:00 (DST: UTC+11:00)
America/New_YorkUTC-05:00 (DST: UTC-04:00)
America/Los_AngelesUTC-08:00 (DST: UTC-07:00)
Pacific/AucklandUTC+12:00 (DST: UTC+13:00)

ZoneId

자바는 타임존을 ZoneId 클래스로 제공한다.

기능

일광 절약 시간, UTC와 오프셋 정보를 포함한다.

메서드설명
of(String zoneId)주어진 타임존 ID를 사용하는 ZoneId 객체를 반환
getId()ZoneId의 ID를 문자열로 반환
getRules()ZoneId에 대한 타임존 규칙(오프셋 정보)을 반환
normalized()표준 형식으로 정규화된 ZoneId 객체를 반환
getAvailableZoneIds()사용 가능한 모든 타임존 ID의 Set을 반환
systemDefault()시스템이 사용하는 기본 ZoneId 반환
from(TemporalAccessor temporal)TemporalAccessor 객체에서 ZoneId를 추출하여 반환

사용해보기

public class ZoneIdMain {
	public static void main(String[] args) {
        // Zone ID 얻기
        for (String id : ZoneId.getAvailableZoneIds()) {
            ZoneId zoneId = ZoneId.of(id);
            System.out.println(zoneId + "|" + zoneId.getRules());
        }

        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println("시스템 타임존: " + zoneId);

        ZoneId seoulZoneId = ZoneId.of("Asia/Seoul");
        System.out.println("서울 타임존: " + seoulZoneId);
        }
    }
}
Asia/Aden|ZoneRules[currentStandardOffset=+03:00]
America/Cuiaba|ZoneRules[currentStandardOffset=-04:00]
...
Europe/Monaco|ZoneRules[currentStandardOffset=+01:00]
시스템 타임존: Asia/Seoul
서울 타임존 오프셋: ZoneRules[currentStandardOffset=+09:00]

ZoneOffset

기능

시간대 오프셋을 분, 초 단위로 나타내며, 고정된 시간 차이를 관리한다.

메서드설명
of(String offsetId)주어진 오프셋 ID 문자열에서 ZoneOffset 객체를 반환
getTotalSeconds()오프셋의 총 초 단위 값을 반환
ofHours(int hours)주어진 시간 값에서 ZoneOffset 객체를 반환
getId()ZoneOffset의 ID를 문자열로 반환
ofHoursMinutes(int hours, int minutes)주어진 시간과 분 값에서 ZoneOffset 객체를 반환
from(TemporalAccessor temporal)TemporalAccessor 객체에서 ZoneOffset을 추출하여 반환

사용해보기

public class ZoneOffsetMain {
    public static void main(String[] args) {
        // ZoneOffset 얻기
        ZoneOffset offset = ZoneOffset.of("+09:00");
        System.out.println("오프셋: " + offset);

        int totalSeconds = offset.getTotalSeconds();
        System.out.println("총 초 단위 오프셋: " + totalSeconds);

        ZoneOffset offsetHours = ZoneOffset.ofHours(9);
        System.out.println("9시간 오프셋: " + offsetHours);

        ZoneOffset offsetHoursMinutes = ZoneOffset.ofHoursMinutes(9, 30);
        System.out.println("9시간 30분 오프셋: " + offsetHoursMinutes);

        ZoneOffset systemOffset = ZoneOffset.from(ZonedDateTime.now());
        System.out.println("시스템 오프셋: " + systemOffset);
    }
}
오프셋: +09:00
총 초 단위 오프셋: 32400
9시간 오프셋: +09:00
9시간 30분 오프셋: +09:30
시스템 오프셋: +09:00

ZonedDateTime

LocalDateTimeZoneId와 `ZoneOffset이 합쳐진 것이다.
시간대를 고려하여 날짜, 시간과 타임존을 표현한다.

public final class ZonedDateTime
        implements Temporal, ChronoZonedDateTime<LocalDate>, Serializable {
	...
    private final LocalDateTime dateTime;
    private final ZoneOffset offset;
    private final ZoneId zone;
    ...
}

기능

메서드설명
now()기본 타임존의 현재 날짜와 시간으로 ZonedDateTime 객체를 반환
of(LocalDate date, LocalTime time, ZoneId zone)주어진 날짜, 시간, 타임존으로 ZonedDateTime 객체를 반환
withZoneSameInstant(ZoneId zone)동일한 순간을 다른 시간대로 변환하여 새로운 ZonedDateTime 객체를 반환
toLocalDateTime()ZonedDateTime 객체에서 LocalDateTime 부분을 반환
getZone()ZonedDateTime 객체의 ZoneId를 반환
getOffset()ZonedDateTime 객체의 ZoneOffset을 반환

사용해보기

public class ZonedDateTimeMain {
	public static void main(String[] args) {
        // 1. ZonedDateTime 생성
        // 1-1. now
        ZonedDateTime nowZdt = ZonedDateTime.now();
        System.out.println("현재 시간(now): " + nowZdt);

        // 1-2. of
        ZonedDateTime ofZdt = ZonedDateTime.of(2024, 5, 31, 
                15, 10, 30, 10, ZoneId.of("Asia/Seoul"));
        System.out.println("지정 시간(of): " + ofZdt);

        // 1-3. LocalDateTime + ZoneId
        LocalDateTime localDt = LocalDateTime.of(2024, 5, 31, 21, 15, 40);
        ZonedDateTime zonedDt = ZonedDateTime.of(localDt, ZoneId.of("Asia/Seoul"));
        System.out.println("지정 시간(LocalDateTime+ZoneId): " + zonedDt);

        // 2. 타임존 변경
        ZonedDateTime utcZdt = zonedDt.withZoneSameInstant(ZoneId.of("UTC"));
        System.out.println("Asia/Seoul -> UTC 변경된 시간" + utcZdt);
    }
}
현재 시간(now): 2024-06-04T00:23:36.687429+09:00[Asia/Seoul]
지정 시간(of): 2024-05-31T15:10:30.000000010+09:00[Asia/Seoul]
지정 시간(LocalDateTime+ZoneId): 2024-05-31T21:15:40+09:00[Asia/Seoul]
Asia/Seoul -> UTC 변경된 시간2024-05-31T12:15:40Z[UTC]

OffsetDateTime

OffsetDateTimeLocalDateTimeZoneOffset이 합쳐진 것이다.
ZoneId가 없기 때문에 타임존은 없고, 오프셋만 포함한다.

public final class OffsetDateTime
        implements Temporal, TemporalAdjuster, Comparable<OffsetDateTime>, Serializable {
        ...
        private final LocalDateTime dateTime;
	    private final ZoneOffset offset;
        ...
}

기능

메서드설명
now()기본 시간대의 현재 날짜와 시간으로 OffsetDateTime 객체를 반환
of(LocalDate date, LocalTime time, ZoneOffset offset)주어진 날짜, 시간, 오프셋으로 OffsetDateTime 객체를 반환
withOffsetSameInstant(ZoneOffset offset)동일한 순간을 다른 오프셋으로 변환하여 새로운 OffsetDateTime 객체를 반환
toLocalDateTime()OffsetDateTime 객체에서 LocalDateTime 부분을 반환
getOffset()OffsetDateTime 객체의 ZoneOffset을 반환
from(TemporalAccessor temporal)TemporalAccessor 객체에서 OffsetDateTime을 추출하여 반환

사용해보기

public class OffsetDateTimeMain {
	public static void main(String[] args) {
    	// OffsetDateTime 생성
    	// 1. now
        OffsetDateTime nowOdt = OffsetDateTime.now();
        System.out.println("현재 시간: " + nowOdt);

		// 2. LocalDateTime + ZoneOffset
        LocalDateTime localDt = LocalDateTime.of(2024, 5, 31, 19, 30, 50);
        OffsetDateTime offsetDt = OffsetDateTime.of(localDt, ZoneOffset.of("+07:00"));
        System.out.println("지정 시간: " + offsetDt);
    }
}
현재 시간: 2024-06-04T00:36:56.595396+09:00
지정 시간: 2024-05-31T19:30:50+07:00

ZonedDateTimte과 OffsetDateTime 비교

  1. ZonedDateTime
    • 구체적인 지역 시간대를 다룰 때 사용
    • 일광 절약 시간을 자동으로 처리 가능
    • 사용자 지정 시간대에 따른 시간 계산에 적합
  2. OffsetDateTime
    • UTC와 시간 차이만 나타낼 때 사용
    • 지역 시간대의 복잡성을 고려하지 않음
    • 시간대 변환없이 로그 기록이나 데이터 저장 및 처리에 적합

참고
Class ZoneId
Class ZoneOffset
Class ZonedDateTime
Class OffsetDateTime
Java의 정석
김영한의 실전 자바 - 중급 1편

profile
공부 기록

0개의 댓글

관련 채용 정보