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

yal*_*man 4 java timezone datetime

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

TimeZone timeZone = TimeZone.getDefault();
String zoneId = timeZone.getId();  // "America/Chicago"
Run Code Online (Sandbox Code Playgroud)

我的zoneId是"America/Chicago".

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

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

And*_*eas 22

要将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));
Run Code Online (Sandbox Code Playgroud)
2015-10-10T11:00:00
Run Code Online (Sandbox Code Playgroud)

如果您跳过最后一步,则保留该区域.

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