Close

Java Date Time - ZonedDateTime.ofLocal() Examples

Java Date Time Java Java API 


Class:

java.time.ZonedDateTime

java.lang.Objectjava.lang.Objectjava.time.ZonedDateTimejava.time.ZonedDateTimejava.time.temporal.TemporalTemporaljava.time.chrono.ChronoZonedDateTimeChronoZonedDateTimejava.io.SerializableSerializableLogicBig

Method:

public static ZonedDateTime ofLocal(LocalDateTime localDateTime,
                                    ZoneId zone,
                                    ZoneOffset preferredOffset)

Returns an instance of ZonedDateTime from a date-time, zone id and a preferred offset. This method internally finds a valid offset from UTC/Greenwich for the local date-time as defined by the rules of the zone ID. In most cases, there is only one valid offset for a local date-time. In the case of an overlap (DST) there are two valid offsets. If the preferred offset is one of the valid offsets then it is used. Otherwise the earlier valid offset is used.

Examples


package com.logicbig.example.zoneddatetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class OfLocalExample {

public static void main(String... args) {
ZonedDateTime d = ZonedDateTime.ofLocal(LocalDateTime.now(),
ZoneId.of("US/Central"), ZoneOffset.ofHours(-5));
System.out.println(d);

//dst overlap
ZonedDateTime d2 = ZonedDateTime.ofLocal(LocalDateTime.of(2017, 11, 5, 1, 10),
ZoneId.of("US/Central"), ZoneOffset.ofHours(-5));
System.out.println(d2);

//offset -6 is also valid on the overlap
ZonedDateTime d3 = ZonedDateTime.ofLocal(LocalDateTime.of(2017, 11, 5, 1, 10),
ZoneId.of("US/Central"), ZoneOffset.ofHours(-6));
System.out.println(d3);
}
}

Output

2017-05-01T16:01:22.267-05:00[US/Central]
2017-11-05T01:10-05:00[US/Central]
2017-11-05T01:10-06:00[US/Central]




See Also