The static method LocalTime.from(TemporalAccessor temporal) returns the LocalTime instance based on the provided TemporalAccessor.
The provided temporal accessor must have all fields needed for the LocalTime instance to be created otherwise DateTimeException
will be thrown.
package com.logicbig.example.localtime;
import java.time.LocalDateTime;
import java.time.LocalTime;
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());
System.out.println(z);
LocalTime t2 = LocalTime.from(z);
System.out.println(t2);
}
}
Output
2016-10-12T15:20:30-05:00[America/Chicago]
15:20:30
package com.logicbig.example.localtime;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class FromExample3 {
public static void main (String... args) {
OffsetDateTime d = OffsetDateTime.of(2016, 10, 12,
15, 20, 30, 0,
ZoneOffset.of("-06:30"));
System.out.println(d);
LocalTime t2 = LocalTime.from(d);
System.out.println(t2);
}
}
Output
2016-10-12T15:20:30-06:30
15:20:30
package com.logicbig.example.localtime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class FromExample4 {
public static void main (String... args) {
LocalDate d = LocalDate.of(2016, 10, 12);
System.out.println(d);
LocalTime t2 = LocalTime.from(d);
System.out.println(t2);
}
}
Output
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: 2016-10-12 of type java.time.LocalDate
at java.time.LocalTime.from(LocalTime.java:409)
at com.logicbig.example.localtime.FromExample4.main(FromExample4.java:19)
... 6 more