How can I create a Java 8 LocalDate from a long Epoch period in milliseconds?

I have an external API that returns me dates as long s, represented as milliseconds from the era.

Using the old style Java API, I would just build a Date from it with

Date myDate = new Date(startDateLong)

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

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

+67
java datetime java-8 java-time
Feb 03 '16 at 16:58
source share
3 answers

If you have milliseconds from an era and want to convert them to a local date using the current local time zone, you can use

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

but keep in mind that even the default time zone for systems can change, so the same long value can give different results in subsequent runs even on the same computer.

Also, keep in mind that LocalDate , unlike java.util.Date , does represent a date, not a date and time.

Otherwise, you can use LocalDateTime :

 LocalDateTime date = LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault()); 
+127
Feb 03 '16 at 20:27
source share

You can start with Instant.ofEpochMilli (long) :

 LocalDate date = Instant.ofEpochMilli(startDateLong) .atZone(ZoneId.systemDefault()) .toLocalDate(); 
+15
Feb 03 '16 at 20:24
source share

new Date(startDateLong) and stuff, a very simple alternative to new Date(startDateLong) could be LocalDate.ofEpochDay(startDateLong / 86400000L)

0
Apr 10 '17 at 8:46 on
source share



All Articles