The static method OffsetDateTime.from(TemporalAccessor temporal) returns the OffsetDateTime instance based on the provided TemporalAccessor.
The provided temporal accessor must have all fields needed for the OffsetDateTime instance to be created otherwise DateTimeException
will be thrown.
package com.logicbig.example.offsetdatetime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class FromExample {
public static void main (String... args) {
ZonedDateTime z = ZonedDateTime.of(2016, 10, 12,
15, 20, 30, 0,
ZoneId.systemDefault());
OffsetDateTime d = OffsetDateTime.from(z);
System.out.println(d);
}
}
Output
2016-10-12T15:20:30-05:00
package com.logicbig.example.offsetdatetime;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class FromExample2 {
public static void main (String... args) {
OffsetDateTime d = OffsetDateTime.of(LocalDateTime.now(),
ZoneOffset.ofHours(3));
System.out.println(d);
OffsetDateTime dt = OffsetDateTime.from(d);
System.out.println(dt);
}
}
Output
2017-05-01T16:20:49.632+03:00
2017-05-01T16:20:49.632+03:00
package com.logicbig.example.offsetdatetime;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
public class FromExample3 {
public static void main (String... args) {
OffsetDateTime.from(LocalDateTime.now());
}
}
Output
Caused by: java.time.DateTimeException: Unable to obtain OffsetDateTime from TemporalAccessor: 2017-05-01T23:14:54.780 of type java.time.LocalDateTime
at java.time.OffsetDateTime.from(OffsetDateTime.java:370)
at com.logicbig.example.offsetdatetime.FromExample3.main(FromExample3.java:14)
... 6 more
Caused by: java.time.DateTimeException: Unable to obtain ZoneOffset from TemporalAccessor: 2017-05-01T23:14:54.780 of type java.time.LocalDateTime
at java.time.ZoneOffset.from(ZoneOffset.java:348)
at java.time.OffsetDateTime.from(OffsetDateTime.java:359)
... 7 more