I have an external API that returns me dates as long
s, 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.
Timezones and stuff aside, a very simple alternative to new Date(startDateLong)
could be LocalDate.ofEpochDay(startDateLong / 86400000L)
You can start with Instant.ofEpochMilli(long):
LocalDate date =
Instant.ofEpochMilli(startDateLong)
.atZone(ZoneId.systemDefault())
.toLocalDate();
replace now.getTime() with your long value.
//GET UTC time for current date
Date now= new Date();
//LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
LocalDate localDate = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
I think I have a better answer.
new Timestamp(longEpochTime).toLocalDateTime();
In a specific case where your epoch seconds timestamp comes from SQL or is related to SQL somehow, you can obtain it like this:
long startDateLong = <...>
LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();
Source: Stackoverflow.com