如何在很长的纪元时间内以毫秒为单位创建Java 8 LocalDate? [英] How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?
问题描述
我有一个外部API,我的日期为 long
s,表示为自Epoch以来的毫秒数。
I have an external API return me dates as long
s, represented as milliseconds since Epoch.
With旧式Java API,我只需用它构建一个 Date
With the old style Java API, I would simply construct a Date
from it with
Date myDate = new Date(startDateLong)
Java 8中的等价物 LocalDate
/ LocalDateTime
classes?
What is the equivalent in Java 8's LocalDate
/LocalDateTime
classes?
我有兴趣转换点在我当前的当地时区,由长到 LocalDate
表示的时间。
I am interested in converting the point in time represented by the long to a LocalDate
in my current local timezone.
推荐答案
如果您有自Epoch以来的毫秒数并希望使用当前本地时区将它们转换为本地日期,则可以使用
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();
但请记住,即使系统的默认时区可能会改变,因此相同 long
值可能会在后续运行中产生不同的结果,即使在同一台机器上也是如此。
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.
此外,请记住 LocalDate
,与 java.util.Date
不同,实际上代表的是日期,而不是日期和时间。
Further, keep in mind that LocalDate
, unlike java.util.Date
, really represents a date, not a date and time.
否则,您可以使用 LocalDateTime
:
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
这篇关于如何在很长的纪元时间内以毫秒为单位创建Java 8 LocalDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!