如何将毫秒转换为 ZonedDateTime?

16

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

我有以下代码:

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

这条线

LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);

给我一个错误,说methed millsToLocalDateTime对于类型LocalDateTime未定义


JDK 中没有这样的方法。也许你正在使用 JodaTime。 - Antoniossss
4个回答

23

ZonedDateTimeLocalDateTime不同的

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

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

16

您可以从一个瞬间构造一个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();

11
无论您需要 ZonedDateTimeLocalDateTimeOffsetDateTime 还是 LocalDate,语法都非常相似,所有操作都围绕着首先将毫秒应用于 Instant,使用 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

2

在Java中,您无法创建扩展方法。如果您想为此定义一个单独的方法,请创建一个实用类:

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;
    }
}

从您的另一个类调用

DateUtils.millsToLocalDateTime(89897987989L);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接