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

Ted*_*tel 10 java java-time

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

我有以下代码

long m = System.currentTimeMillis();
LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);
Run Code Online (Sandbox Code Playgroud)

线

LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);
Run Code Online (Sandbox Code Playgroud)

给我一个错误,说本地日期时间类型未定义methed millsToLocalDateTime

孙兴斌*_*孙兴斌 13

ZonedDateTime并且LocalDateTime不同的

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

long m = ...;
Instant instant = Instant.ofEpochMilli(m);
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
Run Code Online (Sandbox Code Playgroud)


ern*_*t_k 9

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

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

如果你需要一个LocalDateTime实例:

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


And*_*eas 7

无论您想要ZonedDateTime, LocalDateTime, OffsetDateTime, 或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());
Run Code Online (Sandbox Code Playgroud)

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

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());
Run Code Online (Sandbox Code Playgroud)

打印Instant本身会产生:

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
Run Code Online (Sandbox Code Playgroud)