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

纵饮孤独 提交于 2019-11-26 10:16:06

问题


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.


回答1:


If you have the milliseconds since the Epoch and want 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());



回答2:


You can start with Instant.ofEpochMilli(long):

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



回答3:


I think I have a better answer.

new Timestamp(longEpochTime).toLocalDateTime();



回答4:


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




回答5:


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();


来源:https://stackoverflow.com/questions/35183146/how-can-i-create-a-java-8-localdate-from-a-long-epoch-time-in-milliseconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!