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

时间:2017-02-16 17:08:57

标签: java datetime timezone

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

var recognition = new window.webkitSpeechRecognition

我的zoneId是“America / Chicago”。

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

更重要的是,无论我在哪个时区,有没有办法可以将我的LocalDateTime转换为东部时间(即带有zoneId“America / New_York”的时区)?我正在寻找一种方法来处理过去生成的任何LocalDateTime对象,而不一定是当前时间。

1 个答案:

答案 0 :(得分:17)

要将LocalDateTime转换为其他时区,请先使用atZone()应用原始时区,然后返回ZonedDateTime,然后使用{{3转换为新时区最后将结果转换回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

如果你跳过最后一步,你就会保留这个区域。

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]
相关问题