【问题标题】:Java: ZonedDateTime - get the offset of a reference timestampJava: ZonedDateTime - 获取参考时间戳的偏移量
【发布时间】:2019-04-03 14:09:39
【问题描述】:

我有一个 UTC 时间戳。我将其转换为当地时间。我的时区是 CET/CEST。

2018-10-03 12:00 UTC => 14:00 CEST
2018-10-30 12:00 UTC => 13:00 CET

由于我的时区,系统会自动应用正确的偏移量:如果我在夏季转换时间戳,它会自动增加 2 小时(无论我转换的时间是什么时候),如果是在冬季,它会增加 1 小时。

到目前为止 - 非常好。

现在我想根据另一个引用的时间戳转换 UTC 时间戳。 如果引用在夏季,则应始终添加 2 小时 - 无论要转换的时间戳是夏季还是冬季 - 如果引用在冬季,则应始终添加 1 小时。

Ref = 01.01.2018 = CET
2018-10-03 12:00 UTC => 13:00 CET
2018-10-30 12:00 UTC => 13:00 CET

Ref = 01.10.2018 = CEST
2018-10-03 12:00 UTC => 14:00 CEST
2018-10-30 12:00 UTC => 14:00 CEST

那么,如果我的系统运行正常的 CEST/CET,我如何才能找出参考时间戳(以 UTC 为单位)的时区(或与 UTC 的偏移量)??

我正常使用 ZonedDateTime。

【问题讨论】:

    标签: java datetime zoneddatetime


    【解决方案1】:

    如果日期是 UTC,您可以将日期从字符串解析为 Date 对象,然后您可以将它们转换回本地时区中的字符串。请查看以下代码示例:

            SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date date = isoFormat.parse("2018-10-03 12:00");
    
            isoFormat.setTimeZone(TimeZone.getDefault());
            System.out.println("Date in my local timezone is "+isoFormat.format(date));
    

    【讨论】:

    • 您不应该在新代码中使用Date 类。使用 java.time 包中提供的新日期和时间 API 中的类。
    【解决方案2】:

    您可以从您拥有的参考ZonedDateTime 中获取ZoneId,并使用它来将您在UTC 中拥有的时间戳调整到该区域:

    设置

        ZoneId cet = ZoneId.of("CET");
    
        // The reference timestamps, these could be any ZonedDateTime
        // but I specifically make one for winter and one for summer
        ZonedDateTime refWinter = ZonedDateTime.of(LocalDateTime.parse("2018-01-01T12:00"), cet);
        ZonedDateTime refSummer = ZonedDateTime.of(LocalDateTime.parse("2018-10-01T12:00"), cet);
    
        // The UTC timestamp that you want to convert to the reference zone
        ZonedDateTime utc = ZonedDateTime.of(LocalDateTime.parse("2018-10-03T12:00"), ZoneOffset.UTC);
    

    转化

        // The converted timestamps
        ZonedDateTime convertedWinter = utc.withZoneSameInstant(refWinter.getOffset());
        ZonedDateTime convertedSummer = utc.withZoneSameInstant(refSummer.getOffset());
    
        System.out.println(convertedWinter); // 2018-01-03T13:00+01:00
        System.out.println(convertedSummer); // 2018-10-03T14:00+02:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多