Starting with JDK 8

Starting with JDK 8, there are two classes responsible for dealing with time zone representations. First, there is java.time.ZoneId, which represents a time zone such as Athens, Europe, and second there is java.time.ZoneOffset (extends ZoneId), which represents the fixed amount of time (offset) of the specified time zone with GMT/UTC.

The new Java date-time API deals with Daylight Saving Time by default; therefore, a region with summer-winter cycles that uses Daylight Saving Time will have two ZoneOffset classes.

The UTC zone offset can be easily obtained as follows (this is +00:00, represented in Java by the Z character):

// Z
ZoneOffset zoneOffsetUTC = ZoneOffset.UTC;

The system default time zone can also be obtained via the ZoneOffset class:

// Europe/Athens
ZoneId defaultZoneId = ZoneOffset.systemDefault();

In order to take the zone offset with Daylight Saving Time, the code needs to associate a date-time with it. For example, associate a LocalDateTime class (Instant can also be used) like this:

// by default it deals with the Daylight Saving Times
LocalDateTime ldt = LocalDateTime.of(2019, 6, 15, 0, 0);
ZoneId zoneId = ZoneId.of("Europe/Bucharest");

// +03:00
ZoneOffset zoneOffset = zoneId.getRules().getOffset(ldt);

A zone offset can also be obtained from a string. For example, the following code obtains a zone offset of +02:00:

ZoneOffset zoneOffsetFromString = ZoneOffset.of("+02:00");

This is a very convenient approach of quickly adding a zone offset to a Temporal object that supports zone offsets. For example, use it to add a zone offset to OffsetTime and  OffsetDateTime (convenient ways for storing a date in a database, or sending over the wires):

OffsetTime offsetTime = OffsetTime.now(zoneOffsetFromString);
OffsetDateTime offsetDateTime
= OffsetDateTime.now(zoneOffsetFromString);

Another solution to our problem is to rely on defining ZoneOffset from hours, minutes, and seconds. One of the helper methods of ZoneOffset is dedicated to this:

// +08:30 (this was obtained from 8 hours and 30 minutes)
ZoneOffset zoneOffsetFromHoursMinutes
= ZoneOffset.ofHoursMinutes(8, 30);
Next to ZoneOffset.ofHoursMinutes(), there is ZoneOffset.ofHours(), ofHoursMinutesSeconds() and ofTotalSeconds().

Finally, every Temporal object that supports a zone offset provides a handy getOffset() method. For example, the following code gets the zone offset from the preceding offsetDateTime object:

// +02:00
ZoneOffset zoneOffsetFromOdt = offsetDateTime.getOffset();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.56.12