Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a LocalDate to an Instant?

People also ask

How do I get LocalDate from instant?

Get Instant object which you want to convert to LocalDate. Create ZoneId instance based on Location. Pass ZoneId to atZone() method to get ZoneDateTime . Call toLocalDate() on ZoneDateTime object to get LocalDate .

Can we convert LocalDate to date?

Convert LocalDate To Date in Java Step 1: First Create the LocalDate object using either now() or of() method. now() method gets the current date where as of() creates the LocalDate object with the given year, month and day. Step 2: Next, Get the timezone from operating system using ZoneId. systemDefault() method.

Which class do you use to convert from the local time line to the instant timeline?

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.

How do I create a LocalDate instance?

The easiest way to create an instance of the LocalDateTime class is by using the factory method of(), which accepts year, month, day, hour, minute, and second to create an instance of this class. A shortcut to create an instance of this class is by using atDate() and atTime() method of LocalDate and LocalTime class.


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

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

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