如何从以毫秒为单位的长纪元时间创建 Java 8 LocalDate? [英] How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

查看:33
本文介绍了如何从以毫秒为单位的长纪元时间创建 Java 8 LocalDate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个外部 API,它以 long 的形式返回日期,表示为自纪元开始以来的毫秒数.

I have an external API that returns me dates as longs, represented as milliseconds since the beginning of the Epoch.

使用旧式 Java API,我只需使用

With the old style Java API, I would simply construct a Date from it with

Date myDate = new Date(startDateLong)

Java 8 的 LocalDate/LocalDateTime 类中的等价物是什么?

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

我有兴趣将 long 表示的时间点转换为当前本地时区中的 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 to 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.

此外,请记住,LocalDatejava.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆