【问题标题】:Java convert UTC / CET timeJava转换UTC/CET时间
【发布时间】:2017-03-27 09:33:22
【问题描述】:

我想将给定的日期时间(UTC 日期时间)转换为 CET 中的相应日期时间,并正确映射欧洲夏季/冬季时间开关(夏令时)。我使用java.time 设法相反(CET 到 UTC):

public static LocalDateTime cetToUtc(LocalDateTime timeInCet) {
    ZonedDateTime cetTimeZoned = ZonedDateTime.of(timeInCet, ZoneId.of("CET"));
    return cetTimeZoned.withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

但我没有走相反的路:

public static LocalDateTime utcToCet(LocalDateTime timeInUtc) {
     ZonedDateTime cetTimeZoned = ZonedDateTime.of(timeInUtc,ZoneId.of("UTC"));
     return cetTimeZoned.withZoneSameInstant(ZoneOffset.of(???)).toLocalDateTime(); // what to put here?
 }

我该怎么做?

【问题讨论】:

  • 为什么不使用ZoneId.of("CET")
  • @Jerry06 好的,谢谢,这行得通。我并没有真正意识到我也可以使用Zone 而不是ZoneOffset

标签: java timezone


【解决方案1】:

只需使用 ZoneId.of("CET")

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class Main {

    public static void main(String args[])
    {
        LocalDateTime date = LocalDateTime.now(ZoneId.of("CET"));
        System.out.println(date);

        LocalDateTime utcdate = cetToUtc(date);
        System.out.println(utcdate);

        LocalDateTime cetdate = utcToCet(utcdate);
        System.out.println(cetdate);
    }

    public static LocalDateTime cetToUtc(LocalDateTime timeInCet) {
        ZonedDateTime cetTimeZoned = ZonedDateTime.of(timeInCet, ZoneId.of("CET"));
        return cetTimeZoned.withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
    }

    public static LocalDateTime utcToCet(LocalDateTime timeInUtc) {
         ZonedDateTime utcTimeZoned = ZonedDateTime.of(timeInUtc,ZoneId.of("UTC"));
         return utcTimeZoned.withZoneSameInstant(ZoneId.of("CET")).toLocalDateTime();
     }
}

【讨论】:

    【解决方案2】:

    TL;DR:在您的两种方法中都使用 ZoneId.of("Europe/Rome")(或您在 CET 时区中您最喜欢的城市)和 ZoneOffset.UTC

    正如 Jerry06 在评论中所说,使用 ZoneId.of("CET") 再次有效(您已经在第一个方法中使用了它)。

    但是,不建议使用三个字母的时区缩写,其中很多都是模棱两可的。他们建议您改用其中一个城市时区 ID,例如 ZoneId.of("Europe/Rome") 用于 CET(这将从昨天开始为您提供 CEST)。他们推荐ZoneOffset.UTC,而不是ZoneId.of("UTC")。传递ZoneOffset 有效,因为ZoneOffsetZoneId 的子类之一。

    【讨论】:

      猜你喜欢
      • 2020-08-18
      • 1970-01-01
      • 2022-01-11
      • 2020-05-28
      • 1970-01-01
      • 2019-03-31
      • 2014-11-23
      • 2021-04-21
      • 2015-09-26
      相关资源
      最近更新 更多