如何将以毫秒为单位的时间转换为 ZonedDateTime

How can I convert a time in milliseconds to ZonedDateTime

我有以毫秒为单位的时间,我需要将它转换为 ZonedDateTime 对象。

我有以下代码

long m = System.currentTimeMillis();
LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);

LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);

给我一个错误提示 未定义类型 LocalDateTime

的 methed millsToLocalDateTime

ZonedDateTimeLocalDateTime

如果你需要LocalDateTime,你可以这样做:

long m = ...;
Instant instant = Instant.ofEpochMilli(m);
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

你可以从瞬间构造一个ZonedDateTime(这使用系统区域ID):

//Instant is time-zone unaware, the below will convert to the given zone
ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(m), 
                                ZoneId.systemDefault());

如果您需要一个 LocalDateTime 实例:

//And this date-time will be "local" to the above zone
LocalDateTime ldt = zdt.toLocalDateTime();

您不能在 Java 中创建扩展方法。如果您想为此定义一个单独的方法,请创建一个 Utility class:

class DateUtils{

    public static ZonedDateTime millsToLocalDateTime(long m){
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = Instant.ofEpochSecond(m);
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
        return zonedDateTime;
    }
}

来自你的另一个 class 电话

DateUtils.millsToLocalDateTime(89897987989L);

是否要 ZonedDateTime, LocalDateTime, OffsetDateTime, or LocalDate, the syntax is really the same, and all revolves around applying the milliseconds to an Instant first using Instant.ofEpochMilli(m).

long m = System.currentTimeMillis();

ZonedDateTime  zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
LocalDateTime  ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
OffsetDateTime odt = OffsetDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
LocalDate      ld  = LocalDate.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());

打印它们会产生这样的结果:

2018-08-21T12:47:11.991-04:00[America/New_York]
2018-08-21T12:47:11.991
2018-08-21T12:47:11.991-04:00
2018-08-21

打印 Instant 本身会产生:

2018-08-21T16:47:11.991Z