Returns an instance of ZonedDateTime strictly validating the combination of local date-time, offset and zone ID.
This creates a zoned date-time ensuring that the offset is valid for the local date-time according to the rules of the specified zone. If the offset is invalid, an exception is thrown.
package com.logicbig.example.zoneddatetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class OfStrictExample {
public static void main(String... args) {
ZonedDateTime d = ZonedDateTime.ofStrict(LocalDateTime.now(),
ZoneOffset.ofHours(-5), ZoneId.of("US/Central"));
System.out.println(d);
}
}
Output
2017-05-01T16:01:17.951-05:00[US/Central]
For an invalid value of offset will throw the DateTimeException:
package com.logicbig.example.zoneddatetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class OfStrictExample2 {
public static void main(String... args) {
//For CST offset -5 is only valid during DST. Using offset of -6 will fix the exception
ZonedDateTime d = ZonedDateTime.ofStrict(LocalDateTime.of(2017, 1, 1, 23, 40, 10),
ZoneOffset.ofHours(-5), ZoneId.of("US/Central"));
System.out.println(d);
}
}
Output
Caused by: java.time.DateTimeException: ZoneOffset '-05:00' is not valid for LocalDateTime '2017-01-01T23:40:10' in zone 'US/Central'
at java.time.ZonedDateTime.ofStrict(ZonedDateTime.java:488)
at com.logicbig.example.zoneddatetime.OfStrictExample2.main(OfStrictExample2.java:18)
... 6 more