【发布时间】:2017-01-19 22:58:31
【问题描述】:
我对 java 时间中的时间处理感到困惑。我长期工作的假设是,如果将时间戳指定为祖鲁时间,java 会处理与本地时间有关的偏移量。
为了说明。我目前在 BST,其偏移量为 UTC +1。考虑到这一点,我希望这个祖鲁时间:
2016-09-12T13:15:17.309Z
成为
2016-09-12T14:15:17.309
LocalDateTime 解析后。这是因为我的默认系统时间设置为 BST 并且上面的时间戳(祖鲁时间)指定它是 UTC 时间。
但请考虑以下示例:
String ts = "2016-09-12T13:15:17.309Z";
LocalDateTime parse = LocalDateTime.parse(ts, DateTimeFormatter.ISO_DATE_TIME);
System.out.println(parse);
这将打印:
2016-09-12T13:15:17.309
因此,解析为 LocalDateTime 的时间戳不会被识别为 UTC 时间,而是直接被视为本地时间。 所以我想,也许我需要将它解析为 ZonedDateTime 并专门将其转换为 LocalDateTime 以获得正确的本地时间。通过这个测试:
String ts = "2016-09-12T13:15:17.309Z";
ZonedDateTime parse = ZonedDateTime.parse(ts, DateTimeFormatter.ISO_DATE_TIME);
System.out.println(parse);
System.out.println(parse.toLocalDateTime());
我得到了输出:
2016-09-12T13:15:17.309Z
2016-09-12T13:15:17.309
两个日期的输出相同。
我能找到的正确解析这个的唯一方法是:
String ts = "2016-09-12T13:15:17.309Z";
Instant instant = Instant.parse(ts); // parses UTC
LocalDateTime ofInstant = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println(instant);
System.out.println(ofInstant);
打印出来:
2016-09-12T13:15:17.309Z
2016-09-12T14:15:17.309
哪个是正确的。
所以问题是:
- Java 时间不应该识别 UTC 时间戳并将其解析为正确的系统默认值吗?
- 如何使用
LocalDateTime#parse方法获得正确的结果? - 我现在应该对所有内容都使用
Instant并放弃解析吗?
问题在于jersey/jackson 的java 时间模块使用ISO 格式和常规LocalDateTime#parse 方法解析时间戳。我意识到我的时代并没有结束,因为它们被视为LocalTime,而实际上它们处于祖鲁时代。
【问题讨论】:
标签: java parsing datetime java-time localtime