Java Reference
In-Depth Information
The ZonedDateTime class contains a static factory method ofLocal(LocalDateTime localDateTime, ZoneId
zone, ZoneOffset preferredOffset) . You can use this method to create a ZonedDateTime by specifying the
preferred zone offset in case there are two zone offsets available for the local time in the specified zone . If the
specified referred zone offset is invalid, the earlier zone offset for the overlap is used. The following snippet of code
demonstrates the use of this method. When I provide an invalid preferred offset -07:00, the earlier offset -05:00 is used.
ZoneId usChicago = ZoneId.of("America/Chicago");
ZoneOffset offset5 = ZoneOffset.of("-05:00");
ZoneOffset offset6 = ZoneOffset.of("-06:00");
ZoneOffset offset7 = ZoneOffset.of("-07:00");
// At 2013-10-03T01:30, -05:00 and -06:00 offsets were valid for
// the time zone America/Chicago
LocalDateTime ldt = LocalDateTime.of(2013, Month.NOVEMBER, 3, 1, 30);
ZonedDateTime zdt5 = ZonedDateTime.ofLocal(ldt, usChicago, offset5);
ZonedDateTime zdt6 = ZonedDateTime.ofLocal(ldt, usChicago, offset6);
ZonedDateTime zdt7 = ZonedDateTime.ofLocal(ldt, usChicago, offset7);
System.out.println("With offset " + offset5 + ": " + zdt5);
System.out.println("With offset " + offset6 + ": " + zdt6);
System.out.println("With offset " + offset7 + ": " + zdt7);
With offset -05:00: 2013-11-03T01:30-05:00[America/Chicago]
With offset -06:00: 2013-11-03T01:30-06:00[America/Chicago]
With offset -07:00: 2013-11-03T01:30-05:00[America/Chicago]
The ZonedDateTime class contains several methods to convert it to local and offset date, time and datetime
representations, compare its instances, and obtain its new instances by changes some of its fields. Listing 12-9 shows
how to work with zoned datetimes. You will get a different output for the current date and time.
Listing 12-9. Using the ZonedDateTime Class
// ZonedDateTimeTest.java
package com.jdojo.datetime;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class ZonedDateTimeTest {
public static void main(String[] args) {
// Get the current zoned datetime for the system default time zone
ZonedDateTime zdt1 = ZonedDateTime.now();
System.out.println("Current zoned datetime:" + zdt1);
// Create a local datetime
LocalDateTime ldt = LocalDateTime.of(2012, Month.MARCH, 11, 7, 30);
 
Search WWH ::




Custom Search