使用 Java 8 时间将时间从一个时区转换为另一时区

2024-04-29

我正在尝试将日期转换为GMT +5:30 to EST与java 8ZonedDateTime.

String inputDate = "2015/04/30 13:00";
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm", Locale.US);
LocalDateTime local = LocalDateTime.parse(inputDate, sourceFormatter);
// local : 2015-04-30T13:00
//Combining this local date-time with a time-zone to create a ZonedDateTime. 
ZonedDateTime zoned = local.atZone(TimeZone.getTimeZone("GMT+5:30").toZoneId());
// zoned : 2015-04-30T13:00+05:30[GMT+05:30]
ZonedDateTime zonedUS = zoned.withZoneSameInstant(TimeZone.getTimeZone("GMT-5:00").toZoneId());
// zonedUS : 2015-04-30T02:30-05:00[GMT-05:00]

我期待着3:30 AM EST但我得到的是2:30 AM EST as 1 PM IST= 3:30AM EST。我缺少什么?


当您指定 EST(东部标准时间)时,您找到的任何服务似乎都对解释您的意思和假定的北美东部夏令时间(EDT)过于有帮助。大多数(并非所有)使用 EST 作为标准时间的地方都使用夏令时,因此在您使用的日期(2015 年 4 月 30 日)处于 EDT 或偏移 UTC-04:00。

如果对您的情况有意义,您应该始终更喜欢以地区/城市格式给出时区,例如亚洲/加尔各答和美国/纽约。如果您想要东部时间,如纽约或蒙特利尔,有人可能会说您的“时区”GMT-5:00 是错误的,这也是导致您意外结果的原因。

所以你的代码变成例如:

    String inputDate = "2015/04/30 13:00";
    DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm", Locale.US);
    LocalDateTime local = LocalDateTime.parse(inputDate, sourceFormatter);
    // local : 2015-04-30T13:00
    //Combining this local date-time with a time-zone to create a ZonedDateTime. 
    ZonedDateTime zoned = local.atZone(ZoneId.of("Asia/Kolkata"));
    // zoned : 2015-04-30T13:00+05:30[Asia/Kolkata]
    ZonedDateTime zonedUS = zoned.withZoneSameInstant(ZoneId.of("America/Montreal"));
    // zonedUS : 2015-04-30T03:30-04:00[America/Montreal]

我做了另一项改变:当使用来自java.time,也没有必要使用过时的TimeZone类,所以我把它拿出来了。代码稍微简单一些,更重要的是,ZoneId.of(String)包括对时区字符串的验证,因此您会发现时区名称中的任何拼写错误(就像我刚刚键入(而不是/在亚洲/加尔各答——这种情况经常发生)。

以上大部分内容已在乔恩·斯基特 (Jon Skeet) 和其他人的评论中说过。我认为值得回答,所以很明显问题已经得到解答。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Java 8 时间将时间从一个时区转换为另一时区 的相关文章

随机推荐