Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

I have an external API that returns me dates as longs, represented as milliseconds since the beginning of the Epoch.

With the old style Java API, I would simply construct a Date from it with

Date myDate = new Date(startDateLong) 

What is the equivalent in Java 8's LocalDate/LocalDateTime classes?

I am interested in converting the point in time represented by the long to a LocalDate in my current local timezone.

like image 246
Vihung Avatar asked Feb 03 '16 16:02

Vihung


People also ask

How do I convert epoch to LocalDate?

The given epoch days, epoch seconds or epoch milliseconds are converted into LocalDate by adding the given time to 1970-01-01T00:00:00Z.

How do I get LocalDate in Java 8?

LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date.

What is milliseconds since epoch?

The number of milliseconds since the "Unix epoch" 1970-01-01T00:00:00Z (UTC). This value is independent of the time zone. This value is at most 8,640,000,000,000,000ms (100,000,000 days) from the Unix epoch. In other words: millisecondsSinceEpoch.


1 Answers

If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use

LocalDate date =     Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate(); 

but keep in mind that even the system’s default time zone may change, thus the same long value may produce different result in subsequent runs, even on the same machine.

Further, keep in mind that LocalDate, unlike java.util.Date, really represents a date, not a date and time.

Otherwise, you may use a LocalDateTime:

LocalDateTime date =     LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault()); 
like image 139
Holger Avatar answered Oct 20 '22 02:10

Holger