Why can I pass a LocalDateTime object to ZonedDateTime.from () if it is not possible to parse a simple date and time?
Both LocalDateTime and ZonedDateTime implements the Temporal interface , which extends TemporalAccessor .
LocalDateTime is a date-time without a time zone in the ISO-8601 calendar system, for example, 2007-12-03T10: 15: 30
ZonedDateTime - - ISO-8601, , 2007-12-03T10: 15: 30 + 01: 00 /.
, from(TemporalAccessor temporal), TemporalAccessor. ZonedDateTime, LocalDateTime TemporalAccessor (Temporal extends TemporalAccessor), ( ), , Zoned .
:
public static ZonedDateTime from(TemporalAccessor temporal) {
if (temporal instanceof ZonedDateTime) {
return (ZonedDateTime) temporal;
}
try {
ZoneId zone = ZoneId.from(temporal);
if (temporal.isSupported(INSTANT_SECONDS)) {
long epochSecond = temporal.getLong(INSTANT_SECONDS);
int nanoOfSecond = temporal.get(NANO_OF_SECOND);
return create(epochSecond, nanoOfSecond, zone);
} else {
LocalDate date = LocalDate.from(temporal);
LocalTime time = LocalTime.from(temporal);
return of(date, time, zone);
}
} catch (DateTimeException ex) {
throw new DateTimeException("Unable to obtain ZonedDateTime from TemporalAccessor: " +
temporal + " of type " + temporal.getClass().getName(), ex);
}
}
.
LocalDateTime.parse("2016-08-31T23:00:59") from(TemporalAccessor temporal). , ZonedDateTime, ZoneId zone = ZoneId.from(temporal);
, , LocalDateTime
.
?
ZonedDateTime
LocalDateTime ldt = LocalDateTime.parse("2016-08-31T23:00:59");
ZoneId zoneId = ZoneId.of("Europe/Paris");
ZonedDateTime zdt = ldt.atZone(zoneId);
GregorianCalendar gc = GregorianCalendar.from(zdt);
Junit
@Test
public void test() throws Exception {
ZoneId zoneId = ZoneId.of("Europe/Paris");
GregorianCalendar.from(LocalDateTime.parse("2016-08-31T23:00:59").atZone(zoneId));
}