java 根据当前时区与东部时区的时差更改 LocalDateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42280454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:30:46  来源:igfitidea点击:

Changing LocalDateTime based on time difference in current time zone vs. eastern time zone

javadatetimetimezone

提问by yalpsid eman

Let's say one week ago I generate a LocalDateTime of 2015-10-10T10:00:00. Furthermore, let's assume I generate my current time zone id as such

假设一周前我生成了 2015-10-10T10:00:00 的 LocalDateTime。此外,假设我生成了当前的时区 ID

TimeZone timeZone = TimeZone.getDefault();
String zoneId = timeZone.getId();  // "America/Chicago"

And my zoneId is "America/Chicago".

我的 zoneId 是“美国/芝加哥”。

Is there an easy way I can convert my LocalDateTime to one for the time zone id "America/New_York" (ie so my updated LocalDateTime would be 2015-10-10T11:00:00)?

有没有一种简单的方法可以将我的 LocalDateTime 转换为时区 ID“America/New_York”(即我更新的 LocalDateTime 将是 2015-10-10T11:00:00)?

More importantly, is there a way I can convert my LocalDateTime to eastern time (ie, to a time zone with zoneId "America/New_York") no matter what time zone I am in? I am specifically looking for a way to do this with any LocalDateTime object generated in the past, and not necessarily for the current time this instant.

更重要的是,有没有一种方法可以将我的 LocalDateTime 转换为东部时间(即转换为 zoneId“America/New_York”的时区),无论我在哪个时区?我正在专门寻找一种方法来使用过去生成的任何 LocalDateTime 对象来执行此操作,而不必针对当前时间立即执行此操作。

回答by Andreas

To convert a LocalDateTimeto another time zone, you first apply the original time zone using atZone(), which returns a ZonedDateTime, then convert to the new time zone using withZoneSameInstant(), and finally convert the result back to a LocalDateTime.

要将 a 转换LocalDateTime为另一个时区,首先使用 应用原始时区atZone(),返回 a ZonedDateTime,然后使用 转换为新时区withZoneSameInstant(),最后将结果转换回 a LocalDateTime

LocalDateTime oldDateTime = LocalDateTime.parse("2015-10-10T10:00:00");
ZoneId oldZone = ZoneId.of("America/Chicago");

ZoneId newZone = ZoneId.of("America/New_York");
LocalDateTime newDateTime = oldDateTime.atZone(oldZone)
                                       .withZoneSameInstant(newZone)
                                       .toLocalDateTime();
System.out.println(newDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
2015-10-10T11:00:00

If you skip the last step, you'd keep the zone.

如果您跳过最后一步,您将保留该区域。

ZonedDateTime newDateTime = oldDateTime.atZone(oldZone)
                                       .withZoneSameInstant(newZone);
System.out.println(newDateTime.format(DateTimeFormatter.ISO_DATE_TIME));
2015-10-10T11:00:00-04:00[America/New_York]