首页 > 解决方案 > 将毫秒转换为 ZonedDateTime 不起作用

问题描述

我有很长的这个毫秒:

1570046362841

使用版本 1转换时:

var myDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1570046362841), ZoneId.of("America/New_York"));

我会得到这个结果(这是错误的!):

+51722-10-16T03:58:54-04:00[America/New_York]

但是,使用版本 2进行转换时:

 final String dateFormat = "yyyy-MM-dd HH:mm:ss SSS";
 SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
 formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
 var dateObj = new Date(1570046362841);
 var myDate = formatter.format(dateObj);

我得到正确的结果:

2019-10-02 15:59:59 934

为什么版本 1 错误?版本 1 有什么问题?

标签: javaepochmillisecondszoneddatetimedate

解决方案


而不是Instant.ofEpochSecond()你需要使用Instant.ofEpochMilli(),因为你有millis。


推荐阅读