I am trying to use consistently the Java 8 date time API, I am looking for explications behind this behaviour :
Instant.from(LocalDateTime.of(2017,01,01,0,0,0,0))
Compiles just fine but yields to :
Exception in thread "main" java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: 2017-01-01T00:00 of type java.time.LocalDateTime
My question is :if these types are not compatible why did the API let me code that and compile it without screaming ?
It compiles fine because
Instant.from(TemporalAccessor temporal)
accepts a TemporalAccessor andLocalDateTime
is a subclass fromTemporalAccessor
.At runtime you get an exception because to create a
Instant
theTemporalAccessor
must have the fieldsINSTANT_SECONDS
andNANO_OF_SECOND
, butLocalDateTime
doesn't provideINSTANT_SECONDS
onlyNANO_OF_SECOND
.To create an Instant from a LocalDateTime better use (for example):
or