且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-07 17:55:52

当您指定 EST (Eastern标准时间).大多数(并非所有)使用 EST 作为标准时间的地方都使用夏令时,因此在您使用的日期(2015 年 4 月 30 日)处于 EDT 或偏移 UTC-04:00.

It seems that whatever service you found was being over-helpful in interpreting what you meant and assumed North American Eastern Daylight Time (EDT) when you specified EST (Eastern Standard Time). Most, not all of the places using EST as standard time are using daylight saving time and hence were on EDT or offset UTC-04:00 on the date you use, April 30, 2015.

如果在您的情况下有意义,您应该始终倾向于以地区/城市格式提供时区,例如 Asia/Kolkata 和 America/New_York.如果您打算使用纽约或蒙特利尔的东部时间,人们可能会说您的时区"格林威治标准时间 5:00 是错误的,这是导致您意外结果的原因.

If it makes sense in your situation, you should always prefer to give time zone in the region/city format, as Asia/Kolkata and America/New_York. If you intended Eastern Time as in New York or Montréal, one may say that your "time zone" of GMT-5:00 was wrong and the cause of your unexpected result.

所以你的代码变成例如:

So your code becomes for example:

    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) 包括对时区字符串的验证,因此您会发现时区名称中的任何拼写错误(就像我刚好输入一个 ( 而不是亚洲/加尔各答的 / - 这种情况一直发生.

I have made one other change: When using the modern classes from java.time, there is no point in also using the outdated TimeZone class, so I have taken that out. The code is slightly simpler, and more importantly, ZoneId.of(String) includes validation of your time zone string so you will discover any spelling error in the time zone name (like when I just happened to type a ( instead of the / in Asia/Kolkata — such happens all the time).

以上大部分内容已在 Jon Skeet 和其他人的评论中说过.我认为它值得进入答案,因此很明显问题已得到解答.

Most of the above has already been said in comments by Jon Skeet and others. I thought it deserved to go into an answer so it’s plain to see that the question has been answered.