首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得SAST的ZoneId?

如何获得SAST的ZoneId?
EN

Stack Overflow用户
提问于 2020-08-03 08:46:51
回答 2查看 1K关注 0票数 3

我需要从这样指定区域的文件中解析时区: UTC、SAST等等。

问题:虽然ZoneId.of("UTC")运行良好,但我不能对SAST做同样的工作。

我得到了java.time.zone.ZoneRulesException: Unknown time-zone ID: SAST

问题:如何将"SAST“字符串转换为ZoneId

我知道,每次我收到它,我都可以用"GMT+2“代替"SAST”,但是如果有一种更优雅的方法,那就太好了。

EN

回答 2

Stack Overflow用户

发布于 2020-08-03 09:10:35

根据oracle文档的说法,南非标准时间是非洲/约翰内斯堡。所以你应该用:

代码语言:javascript
复制
ZoneId.of("Africa/Johannesburg")
票数 6
EN

Stack Overflow用户

发布于 2020-08-03 08:51:37

代码语言:javascript
复制
DisplayZoneAndOffSet.java
package com.mkyong;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class DisplayZoneAndOffSet {

    public static final boolean SORT_BY_REGION = false;

    public static void main(String[] argv) {

        Map<String, String> sortedMap = new LinkedHashMap<>();

        Map<String, String> allZoneIdsAndItsOffSet = getAllZoneIdsAndItsOffSet();

        //sort map by key
        if (SORT_BY_REGION) {
            allZoneIdsAndItsOffSet.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));
        } else {
            // sort by value, descending order
            allZoneIdsAndItsOffSet.entrySet().stream()
                    .sorted(Map.Entry.<String, String>comparingByValue().reversed())
                    .forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));
        }

        // print map
        sortedMap.forEach((k, v) ->
        {
            String out = String.format("%35s (UTC%s) %n", k, v);
            System.out.printf(out);
        });

        System.out.println("\nTotal Zone IDs " + sortedMap.size());

    }

    private static Map<String, String> getAllZoneIdsAndItsOffSet() {

        Map<String, String> result = new HashMap<>();

        LocalDateTime localDateTime = LocalDateTime.now();

        for (String zoneId : ZoneId.getAvailableZoneIds()) {

            ZoneId id = ZoneId.of(zoneId);

            // LocalDateTime -> ZonedDateTime
            ZonedDateTime zonedDateTime = localDateTime.atZone(id);

            // ZonedDateTime -> ZoneOffset
            ZoneOffset zoneOffset = zonedDateTime.getOffset();

            //replace Z to +00:00
            String offset = zoneOffset.getId().replaceAll("Z", "+00:00");

            result.put(id.toString(), offset);

        }

        return result;

    }

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63226340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档