user1643352
user1643352

Reputation: 2917

How to convert a LocalDate to an Instant?

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.

Upvotes: 196

Views: 205474

Answers (3)

paiego
paiego

Reputation: 3787

Using this I'm able to get the local datetime Instance:

LocalDateTime.now().toInstant(ZoneOffset.UTC)

Upvotes: 0

JodaStephen
JodaStephen

Reputation: 63465

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

Upvotes: 232

mdo
mdo

Reputation: 7111

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

LocalDate.now().atStartOfDay().toInstant(ZoneOffset.UTC)

Upvotes: 183

Related Questions