138

I work with the new DateTime API of Java 8.

How to convert a LocalDate to an Instant? I get an exception with

LocalDate date = LocalDate.of(2012, 2, 2);
Instant instant = Instant.from(date);

and I don't understand why.

JodaStephen
  • 53,561
  • 13
  • 87
  • 108
user1643352
  • 2,163
  • 2
  • 16
  • 24

2 Answers2

142

In order to convert it to an instant you need to have a LocalDateTime instance, e.g.:

LocalDate.now().atStartOfDay().toInstant(ZoneOffset.UTC)
mdo
  • 6,293
  • 3
  • 20
  • 26
141

The Instant class represents an instantaneous point on the time-line. Conversion to and from a LocalDate requires a time-zone. Unlike some other date and time libraries, JSR-310 will not select the time-zone for you automatically, so you must provide it.

LocalDate date = LocalDate.now();
Instant instant = date.atStartOfDay(ZoneId.systemDefault()).toInstant();

This example uses the default time-zone of the JVM - ZoneId.systemDefault() - to perform the conversion. See here for a longer answer to a related question.


Update: The accepted answer uses LocalDateTime::toInstant(ZoneOffset) which only accepts ZoneOffset. This answer uses LocalDate::atStartOfDay(ZoneId) which accepts any ZoneId. As such, this answer is generally more useful (and probably should be the accepted one).

PS. I was the main author of the API

JodaStephen
  • 53,561
  • 13
  • 87
  • 108
  • 1
    I think this is the more useful than the accepted answer since ZoneId (timezone) is the parameter and not ZoneOffset (hours shifted from UTC, which may change for a timezone in summer/winter). – wuerg Jun 12 '18 at 12:01
  • 1
    In a unit test I am writing, I have a LocalDate, that is converted to a com.google.protobuf.Timestamp and then mapped back to a LocalDate via an Instant, both ways. When using the approach the accepted answer suggests, I get the expected LocalDate in return, but using this approach gives me "yesterday" back instead of "today". My timezone is GMT+1 – Nadrendion Jan 16 '19 at 07:30