Sub topic 8
Time Zones and Offsets: ZoneId and ZoneOffset
So far you have worked with "local" types such as LocalDate and LocalDateTime. They have no idea where in the world they are. "9:00 on July 1" happens at a different moment in New York than it does in Tokyo. You need a time zone to turn a local time into a real moment.
This chapter covers the two classes Java uses to describe "where": ZoneId and ZoneOffset. The next chapter uses them with ZonedDateTime.
Key Words First
A few terms come up again and again in this chapter:
- UTC is the world's reference time. Every other clock on Earth is described as being ahead of UTC or behind it.
- An offset is a fixed amount of time ahead of UTC or behind it, such as
+05:30or-04:00. - A time zone is a named region, such as
Europe/Paris, where people use the same clock rules. - Daylight saving time (DST) is when a region moves its clocks forward in summer and back in winter.
- Zone rules are the history and schedule of offsets that a region uses.
The most important idea is that a time zone is not the same as an offset. New York has one time zone, but it uses two offsets during a year: -05:00 in winter and -04:00 in summer.
ZoneOffset: A Fixed Distance from UTC
A ZoneOffset is a fixed number of hours and minutes ahead of UTC or behind it. It never changes, and it has no DST.
import java.time.ZoneOffset;
public class OffsetBasics {
public static void main(String[] args) {
ZoneOffset india = ZoneOffset.of("+05:30");
ZoneOffset minusFour = ZoneOffset.ofHours(-4);
ZoneOffset nepal = ZoneOffset.ofHoursMinutes(5, 45);
System.out.println(india); // +05:30
System.out.println(minusFour); // -04:00
System.out.println(nepal); // +05:45
System.out.println(ZoneOffset.UTC); // Z
System.out.println(india.getTotalSeconds()); // 19800
}
}Some things to notice:
ZoneOffset.UTCprints asZ. The letter "Z" is the standard short name for an offset of zero.getTotalSeconds()gives the offset as a number of seconds. 5 hours and 30 minutes is 19,800 seconds.- Offsets do not have to be whole hours. India uses
+05:30and Nepal uses+05:45. - Valid offsets run from
-18:00to+18:00. Anything outside that range throws aDateTimeException.
ZoneId: A Named Region with Rules
A ZoneId names a region, using an ID from the IANA time zone database. That database is a public list of the world's time zone rules, and the JDK ships with a copy. IDs usually look like Area/City.
import java.time.ZoneId;
public class ZoneBasics {
public static void main(String[] args) {
ZoneId paris = ZoneId.of("Europe/Paris");
ZoneId tokyo = ZoneId.of("Asia/Tokyo");
System.out.println(paris); // Europe/Paris
System.out.println(tokyo); // Asia/Tokyo
System.out.println(ZoneId.systemDefault()); // depends on your computer
boolean known = ZoneId.getAvailableZoneIds().contains("America/New_York");
System.out.println(known); // true
}
}ZoneId.systemDefault() returns the zone your computer or server is set to. That value changes from machine to machine, so avoid depending on it in important code. Name the zone you mean.
ZoneId.getAvailableZoneIds() returns a Set<String> of every ID the JDK knows about, which is several hundred. The exact count depends on your JDK version.
How a Zone Finds Its Offset
A ZoneId doesn't store an offset. It holds a ZoneRules object. To get an offset, you ask the rules for the offset at a specific moment. You represent that moment with an Instant.
Here is the same idea in code:
import java.time.Instant;
import java.time.ZoneId;
import java.time.zone.ZoneRules;
public class ZoneRulesDemo {
public static void main(String[] args) {
ZoneRules rules = ZoneId.of("America/New_York").getRules();
Instant winter = Instant.parse("2024-01-15T12:00:00Z");
Instant summer = Instant.parse("2024-07-15T12:00:00Z");
System.out.println(rules.getOffset(winter)); // -05:00
System.out.println(rules.getOffset(summer)); // -04:00
System.out.println(rules.isDaylightSavings(summer)); // true
System.out.println(rules.isFixedOffset()); // false
}
}The zone is the same in both calls, but the offsets differ. If you save only an offset, you lose this information. A fixed -05:00 can't tell you that the clocks will move in March.
ZoneOffset Is Also a ZoneId
ZoneOffset is a subclass of ZoneId. A subclass is a class that extends another class, so you can use it anywhere the parent class is expected. Any method that accepts a ZoneId also accepts a ZoneOffset. An offset's rules are simple: they always return the same offset.
import java.time.ZoneId;
import java.time.ZoneOffset;
public class OffsetAsZone {
public static void main(String[] args) {
ZoneId fromString = ZoneId.of("+02:00");
System.out.println(fromString instanceof ZoneOffset); // true
ZoneOffset plusTwo = ZoneOffset.ofHours(2);
System.out.println(plusTwo.getRules().isFixedOffset()); // true
ZoneId utcRegion = ZoneId.of("UTC");
System.out.println(utcRegion); // UTC
System.out.println(utcRegion.normalized()); // Z
}
}ZoneId.of("UTC") gives a region ID named "UTC". It doesn't give ZoneOffset.UTC. Calling normalized() turns a zone with a fixed offset into the plain ZoneOffset. This matters when you compare zones with equals, because ZoneId.of("UTC").equals(ZoneOffset.UTC) is false.
Comparing the Two
| Question | ZoneId (region) | ZoneOffset |
|---|---|---|
| Example | `Europe/Paris` | `+01:00` |
| Knows about DST? | Yes | No |
| Offset changes during the year? | It can | Never |
| Created with | `ZoneId.of("Area/City")` | `ZoneOffset.of("+hh:mm")`, `ofHours(n)` |
| Best for | Future events and wall-clock times | Recording exact past moments, data exchange |
Common Mistakes
Using Short Names like "PST"
Short names such as "PST" or "IST" are ambiguous. "IST" can mean India, Ireland, or Israel. Java doesn't accept most of them directly:
import java.time.DateTimeException;
import java.time.ZoneId;
public class ShortIds {
public static void main(String[] args) {
try {
ZoneId.of("PST");
} catch (DateTimeException e) {
System.out.println(e.getMessage()); // Unknown time-zone ID: PST
}
ZoneId la = ZoneId.of("PST", ZoneId.SHORT_IDS);
System.out.println(la); // America/Los_Angeles
}
}ZoneId.SHORT_IDS is a built-in map from old short names to full IDs. It exists so older data keeps working. In new code, use the full Area/City ID.
Typos in Zone IDs
ZoneId.of("Europe/Pairs") fails at runtime with a DateTimeException, which is the same exception you saw for "PST". If zone IDs come from users or config files, catch that exception, or check the ID against getAvailableZoneIds() first.
Treating an Offset as a Time Zone
Say you store -05:00 for a weekly meeting in New York. In summer the meeting will show up an hour off. Store the ZoneId for anything scheduled in the future.
Exercises
Exercise
What does this print? System.out.println(ZoneOffset.ofHoursMinutes(-3, -30).getTotalSeconds());
Show answer
It prints -12600. Minus 3 hours and 30 minutes is -(3 × 3600 + 30 × 60) = -12600 seconds. Both parts must have the same sign, so the minutes are also negative.
Exercise
A booking app stores a dentist appointment for next August in Berlin. Should it store the time zone as ZoneId.of("Europe/Berlin") or as ZoneOffset.of("+01:00")? Why?
Show answer
It should use ZoneId.of("Europe/Berlin"). Berlin uses +01:00 in winter and +02:00 in summer. The region ID lets Java apply the correct summer offset in August. A fixed +01:00 would put the appointment one hour off.
Exercise
Write code that prints the offset Australia/Sydney uses at the instant 2024-01-15T00:00:00Z and at 2024-07-15T00:00:00Z.
Show answer
ZoneRules r = ZoneId.of("Australia/Sydney").getRules(); System.out.println(r.getOffset(Instant.parse("2024-01-15T00:00:00Z"))); System.out.println(r.getOffset(Instant.parse("2024-07-15T00:00:00Z"))); It prints +11:00 for January, which is summer in Sydney, and +10:00 for July.