【问题标题】:Need timezone based on the ISO country code and city in Java需要基于 ISO 国家代码和 Java 城市的时区
【发布时间】:2019-10-11 13:59:57
【问题描述】:

我的要求

::: 根据城市和国家代码查找时区。请分享 有什么方法可以找到吗?我不想只选择城市,因为一个城市可以存在于两个或多个国家/地区。

即使在城市基地 - 如果我进入利兹(英国城市),我可以找到时区,但不是所有城市,它什么都不提供。

Set<String> availableTimeZones = ZoneId.getAvailableZoneIds();


    String cityName = Normalizer.normalize(city, Normalizer.Form.NFKD).replaceAll("[^\\p{ASCII}-_ ]", "")
            .replace(' ', '_');

    List<String> possibleTimeZones = availableTimeZones.stream().filter(zid -> zid.endsWith("/" + cityName))
            .collect(Collectors.toList());

【问题讨论】:

  • one city can exist in two or more countries ... 这并不常见,即使确实发生了,很可能城市的两半仍然有相同的时区。
  • 有很多很多方法可以做到这一点。查找可用的网络服务。创建自己的数据库。您没有充分说明您的要求、您可能尝试使用或尚未尝试使用的 API 等等。
  • @Tim,我认为他的意思是一个城市 name,比如“曼彻斯特”,可以在多个国家/地区,而不是在谈论单个实体城市的拆分两个国家之间!
  • 如果你想要世界上所有的城市,你需要考虑的不仅仅是英语
  • 您还有其他信息吗?纬度/经度?机场代码?

标签: timezone


【解决方案1】:
Rough way I found to achieve is -

private static String getSourceLocalTimeZone(String countryCode, String city, String sourceLocalTimeZone) {
        String[] timeZones = com.ibm.icu.util.TimeZone.getAvailableIDs(countryCode);

        for (String timeZone : timeZones) {
            String cityFromTimeZone = null;
            String[] value = timeZone.split("/");
            if (value != null && value.length > 0) {
                cityFromTimeZone = value[value.length - 1].replace("_", " ");
            }
            if (city!=null && city.matches("(.*)" + cityFromTimeZone + "(.*)")) {
                sourceLocalTimeZone = timeZone;
                break;
            }

        }
        if (sourceLocalTimeZone == null || (sourceLocalTimeZone.isEmpty())) {
            if(timeZones.length>0)
            sourceLocalTimeZone = timeZones[0];
        }
        return sourceLocalTimeZone;
    }

Dependency -
<dependency>
            <groupId>com.ibm.icu</groupId>
            <artifactId>icu4j</artifactId>
            <version>4.6</version>
        </dependency>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多