要在不改变实际日期情况下指定ZonedDateTime
的时区,可以使用withZoneSameInstant()
方法。该方法返回一个新的ZonedDateTime
对象,表示与当前对象具有相同的瞬时点,但在指定的时区中。以下是一个示例代码:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// 创建一个ZonedDateTime对象
ZonedDateTime zonedDateTime = ZonedDateTime.of(
LocalDateTime.of(2022, 1, 1, 12, 0), // 指定日期时间
ZoneId.of("Asia/Shanghai") // 指定时区
);
System.out.println("原始时区: " + zonedDateTime.getZone());
System.out.println("原始日期时间: " + zonedDateTime);
// 指定新的时区
ZonedDateTime newZonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println("新时区: " + newZonedDateTime.getZone());
System.out.println("新日期时间: " + newZonedDateTime);
}
}
输出结果:
原始时区: Asia/Shanghai
原始日期时间: 2022-01-01T12:00+08:00[Asia/Shanghai]
新时区: America/New_York
新日期时间: 2021-12-31T23:00-05:00[America/New_York]
在上面的示例中,我们首先创建了一个ZonedDateTime
对象,表示2022年1月1日12:00在亚洲/上海时区的日期时间。然后,我们使用withZoneSameInstant()
方法将时区更改为美国/纽约。由于我们使用的是withZoneSameInstant()
方法,所以日期时间保持不变,只是时区发生了变化。最后,我们打印出了原始和新的时区以及日期时间。