【问题标题】:How can I determine a timezone by the UTC offset and convert the UTC timestamp to any other timezone in Java8?如何通过 UTC 偏移量确定时区并将 UTC 时间戳转换为 Java8 中的任何其他时区?
【发布时间】:2021-11-19 19:33:12
【问题描述】:

我有一个 UTC 时间戳“2021-02-11T09:00:01-07:00”,我需要根据偏移量获取区域 ID。 逻辑应该能够根据任何给定的偏移量获取正确的时区。 这样我就可以将任何 UTC 时间戳转换为任何其他 ZonedDateTime。 请多多指教。

【问题讨论】:

    标签: datetime java-8 timezone-offset datetimeoffset zoneddatetime


    【解决方案1】:

    时区偏移是时区与格林威治/UTC 不同的时间量。这通常是固定的小时数和分钟数,因此您可以从OffsetDateTime 获取偏移量并获得具有匹配偏移量的ZoneId

    OffsetDateTime dateTime = OffsetDateTime.parse(time);
    
    System.out.println(dateTime.getOffset().getId());
    
    ZoneId.getAvailableZoneIds().forEach(z->{
            if(ZonedDateTime.now(ZoneId.of(z)).getOffset().equals(dateTime.getOffset())){
                System.out.println(z);
            }
        });
    

    注意:据我所知,可能有多个 zoneId 具有相同的偏移量,因此您可能需要国家/地区过滤 zoneId 以选择正确的。

    【讨论】:

    • 这是给美国的。我可以看到美国本身有很多选择。
    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 2016-09-05
    • 2013-06-30
    • 2010-09-16
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 2022-11-30
    相关资源
    最近更新 更多