Time zones in Java 8 Date and Time API

I know for a fact that all programmers love working with time zones. Chances are high that you, as a reader of this blog, are also a programmer so I bet you also just love time zones. Let’s see what Java 8 offers as far as time zones are concerned.

Time zones

So far in this series on the date and time in Java 8 we always worked with the local time zone found on your computer. All date-related classes, such as LocalTime or LocalDateTime allow you to easily set the time zone. Here’s an example with the LocalDateTime class:

Where are these string values coming from? They follow what Internet Assigned Numbers Authority (IANA) has in its database. That page doesn’t offer a readable list of time zones, they are only available in compressed .tar.gz files. In case you don’t want to deal with those you can find the time zones on Wikipedia.

You can get the full list of time zones in Java 8 as follows:

Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();

There’s support for 586 time zones which should be enough for all cases.

You can view the default time zone of your environment like this:

ZoneId systemDefault = ZoneId.systemDefault();

…which in my case returned “Europe/Berlin”.

Setting the time zone will also take care of the summer and winter time adjustments automatically.

ZonedDateTime

What if you want to set the parts of the date individually and set the time zone at the same time? We need to turn to the ZonedDateTime class. The static “of” method has many overloads for granular access. Here’s an example that takes a LocalDateTime instance and a ZoneId, we convert the Budapest time to the Brisbane time zone:

The ZonedDateTime class behaves in much the same way as LocalDateTime and has very similar methods, like “plus”, “minus”, “get” etc. I won’t repeat them here, you can check out the following posts to see how they behave:

“until” will be 60 minutes at the time of writing this post as Canada observes Daylight Saving Time whereas Dominica in the Caribbean region does not. “until” will be 120 minutes as soon as DST is over.