How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?
JavaDatetimeJava 8Java TimeJava Problem Overview
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.
Java Solutions
Solution 1 - Java
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());
Solution 2 - Java
You can start with Instant.ofEpochMilli(long):
LocalDate date =
Instant.ofEpochMilli(startDateLong)
.atZone(ZoneId.systemDefault())
.toLocalDate();
Solution 3 - Java
I think I have a better answer.
new Timestamp(longEpochTime).toLocalDateTime();
Solution 4 - Java
Timezones and stuff aside, a very simple alternative to new Date(startDateLong)
could be LocalDate.ofEpochDay(startDateLong / 86400000L)
Solution 5 - Java
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));
Solution 6 - Java
A simple version based on @Michael Piefel answer:
LocalDate myDate = LocalDate.ofEpochDay(Duration.ofMillis(epochMillis).toDays());
Solution 7 - Java
I'm not a big fan of using both instant and localdate in a project.
What i would do:
val calendar = Calendar.getInstance().apply {
//set timeZone because calendar.timeInMillis = UTC milliseconds
//and calender uses the default timezone
timeZone = TimeZone.getTimeZone("UTC")
}
calendar.clear()
calendar.set(localDate.year, localDate.monthValue - 1, localDate.dayOfMonth)
val millis = calendar.timeInMillis
Solution 8 - Java
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();