【发布时间】:2017-11-06 10:09:27
【问题描述】:
我尝试在 2 个地点格式化当前时间:芝加哥和东京
LocalDateTime now = LocalDateTime.now();
ZonedDateTime chicago = now.atZone(ZoneId.of("America/New_York"));
System.out.println("chicago: " + chicago);
System.out.println("Chicago formated: " + chicago.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL)));
ZonedDateTime tokyo = now.atZone(ZoneId.of("Asia/Tokyo"));
System.out.println("Tokyo: " + tokyo);
System.out.println("Tokyo formated: " + tokyo.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL)));
打印出来:
chicago: 2017-11-05T18:19:01.441-05:00[America/New_York]
Chicago formated: 6:19:01 PM EST
Tokyo: 2017-11-05T18:19:01.441+09:00[Asia/Tokyo]
Tokyo formated: 6:19:01 PM JST
下午 6:19:01 为芝加哥和东京印刷。为什么?
感谢 Andreas 使上述代码正常工作。 按照您的逻辑,我尝试使这项工作:
LocalDateTime PCTime = LocalDateTime.now();//Chicago: 7:51:54 PM
ZonedDateTime newYorkTime = PCTime.atZone(ZoneId.of("America/New_York"));
System.out.println("now: " + newYorkTime);
System.out.println("now fmt: " + newYorkTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL)));
ZonedDateTime newYorkTime0 = newYorkTime.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("N.Y. fmt: " + newYorkTime0.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL)));
输出:
now: 2017-11-05T19:51:54.940-05:00[America/New_York]
now fmt: 7:51:54 PM EST
N.Y. fmt: 7:51:54 PM EST
最后一行应该是N.Y. fmt: 8:51:54 PM EST
【问题讨论】:
-
了解
LocalDateTime不是特定的时间点。这只是全球至少 26 小时内可能出现的时刻的粗略概念。在您提供特定时区的上下文之前,它没有任何意义。除非您说“芝加哥下午 6 点”或“东京下午 6 点”,否则说“下午 6 点”是没有意义的。 -
作为already stated in my answer,调用
LocalDateTime.atZone()只是分配一个时区,它不会改变时间。PCTime是 任何 时区的下午 7:51,因此newYorkTime是美国东部标准时间晚上 7:51。如果你想改变时间,你首先要指定PCTime的时区,例如PCTime.atZone(ZoneId.systemDefault())由于系统默认时区用于获取本地时间,然后使用withZoneSameInstant(ZoneId.of("America/New_York"))转换为新时区,如我的回答所示。 -
很好的解释!