指定ZonedDateTime的时区,而不更改实际日期

时间:2018-11-08 09:49:03

标签: java date timezone 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转换为欧洲/巴黎-而不是相反。

3 个答案:

答案 0 :(得分:6)

您可以使用ZonedDateTime.withZoneSameInstant()方法从世界标准时间移至巴黎时间:

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

答案 1 :(得分:0)

 ZonedId zoneId = ZoneId.of("Europe/Paris");
 return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(),zonedId);

尝试定义为欧洲/巴黎的ZoneId

答案 2 :(得分:0)

由于老式Date对象没有任何时区,因此您可以完全忽略UTC,而直接将其转换为欧洲/巴黎:

private static final ZoneId TARGET_ZONE = ZoneId.of("Europe/Paris");

public static LocalDateTime toLocalDateTime(Date date){
    return date.toInstant().atZone(TARGET_ZONE).toLocalDateTime();
}

不过,我不确定为什么要返回LocalDateTime。那就是丢掉信息。在大多数情况下,我会忽略.toLocalDateTime()并从ZonedDateTime返回atZone

相关问题