【问题标题】:Specify timezone of ZonedDateTime without changing the actual date指定 ZonedDateTime 的时区而不更改实际日期
【发布时间】:2019-04-11 19:25:29
【问题描述】:

我有一个 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 转换为欧洲/巴黎 - 而不是相反。

【问题讨论】:

标签: java date timezone zoneddatetime


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

    由于老式的 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() 并从 atZone 返回 ZonedDateTime

    【讨论】:

      【解决方案3】:
       ZonedId zoneId = ZoneId.of("Europe/Paris");
       return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(),zonedId);
      

      尝试将 ZoneId 定义为 Europe/Paris

      【讨论】:

        猜你喜欢
        • 2013-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-14
        相关资源
        最近更新 更多