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 andLocalDateTimeis a subclass fromTemporalAccessor.At runtime you get an exception because to create a
InstanttheTemporalAccessormust have the fieldsINSTANT_SECONDSandNANO_OF_SECOND, butLocalDateTimedoesn't provideINSTANT_SECONDSonlyNANO_OF_SECOND.To create an Instant from a LocalDateTime better use (for example):
or