Sobes.tech
Junior

What is ZonedDateTime?

sobes.tech AI

Answer from AI

ZonedDateTime is a class from the java.time package that represents a date and time with a correct offset from UTC and an associated time zone. It accounts for daylight saving time rules and other specifics of the particular time zone.

Unlike OffsetDateTime, which only stores the offset from UTC, ZonedDateTime holds a reference to a ZoneId object representing the time zone, allowing for correct arithmetic operations with time, considering changes throughout the year.

Main features:

  • Combination: Merges date, time, and time zone.
  • Precision: Considers daylight saving time (DST) transitions and other zone-specific changes.
  • Immutable: ZonedDateTime objects are immutable, like other classes in java.time.

Example creation:

// Creating a ZonedDateTime for a specific moment in a specific zone
ZonedDateTime dateTimeInLondon = ZonedDateTime.of(2023, 10, 26, 10, 30, 0, 0, ZoneId.of("Europe/London"));
System.out.println(dateTimeInLondon);

// Getting the current ZonedDateTime in the system zone
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now);

Uses:

  • Representing events tied to a specific place and time (e.g., concert start time in a certain city).
  • Performing calculations between time points in different time zones considering DST rules.
  • Working with external systems or databases that require specifying a time zone.

Comparison with other classes:

Class Date Time UTC Offset Time Zone Considers DST
LocalDateTime Yes Yes No No No
OffsetDateTime Yes Yes Yes No Partial
ZonedDateTime Yes Yes Yes Yes Yes