如何将以毫秒为单位的时间转换为分区日期时间



我有以毫秒为单位的时间,我需要将其转换为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();

无论你想要一个ZonedDateTimeLocalDateTimeOffsetDateTime,还是LocalDate,语法其实是一样的,都是围绕着首先使用Instant.ofEpochMilli(m)将毫秒应用于Instant

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

不能在 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);

最新更新