Java new time API compiles and break at run time

159 Views Asked by At

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 ?

1

There are 1 best solutions below

2
On BEST ANSWER

It compiles fine because Instant.from(TemporalAccessor temporal) accepts a TemporalAccessor and LocalDateTime is a subclass from TemporalAccessor.

At runtime you get an exception because to create a Instant the TemporalAccessor must have the fields INSTANT_SECONDS and NANO_OF_SECOND, but LocalDateTime doesn't provide INSTANT_SECONDS only NANO_OF_SECOND.

To create an Instant from a LocalDateTime better use (for example):

LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zoneId).toInstant();

or

LocalDateTime localDateTime = LocalDateTime.now();
Instant instant = localDateTime.toInstant(ZoneOffset.ofHours(0));