首页 > 解决方案 > 指定 ZonedDateTime 的时区而不更改实际日期

问题描述

我有一个包含日期(不是当前日期)的 Date 对象,我需要以某种方式指定该日期为 UTC,然后将其转换为 +1 小时的“欧洲/巴黎”。

public static LocalDateTime toLocalDateTime(Date date){
    return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC), ZoneId.of("Europe/Paris")).toLocalDateTime();
}

给定日期“2018-11-08 15:00:00”,这会将日期转换为“2018-11-08 14:00:00”。我需要它从 UTC 转换为欧洲/巴黎 - 而不是相反。

标签: javadatetimezonezoneddatetime

解决方案


您可以使用ZonedDateTime.withZoneSameInstant()方法从 UTC 移动到巴黎时间:

Date date = new Date();
ZonedDateTime utc = date.toInstant().atZone(ZoneOffset.UTC);
ZonedDateTime paris = utc.withZoneSameInstant(ZoneId.of("Europe/Paris"));
System.out.println(utc);
System.out.println(paris);
System.out.println(paris.toLocalDateTime());

打印:

2018-11-08T10:25:18.223Z
2018-11-08T11:25:18.223+01:00[Europe/Paris]
2018-11-08T11:25:18.223

推荐阅读