【问题标题】:Get timezone ID from human-readable timezone string从人类可读的时区字符串中获取时区 ID
【发布时间】:2013-09-22 04:49:06
【问题描述】:

有没有一种方法可以将 Eastern Standard Time 这样的人类可读时区字符串转换为时区 ID 而无需硬编码?

如果我获得了时区 ID,那么我可以相应地设置时区。

【问题讨论】:

    标签: java android time timezone


    【解决方案1】:

    您可以使用TimeZone 类来枚举时区ID 和字符串。您还可以从字符串值设置 TimeZone。

    TimeZone 类和 Locale 类可用于在当前或某个指定时区中找到合适的时区名称。例如,这个代码片段

    final Locale fr_FR = Locale.FRANCE;
    final Locale de_DE = Locale.GERMANY;
    for (String s : TimeZone.getAvailableIDs()) {
        final TimeZone tz = TimeZone.getTimeZone(s);
        sb.append(tz.getDisplayName() + "<br>");
        sb.append(tz.getDisplayName(fr_FR) + "<br>");
        sb.append(tz.getDisplayName(de_DE) + "<br>");
        sb.append("<br>");
    }
    

    列出一些欧洲时区的以下名称:

    Eastern European Standard Time
    heure normale de l’Europe de l’Est
    Osteuropäische Normalzeit
    
    Western European Standard Time
    heure normale d’Europe de l’Ouest
    Westeuropäische Normalzeit
    
    Central European Standard Time
    heure normale de l’Europe centrale
    Mitteleuropäische Normalzeit
    

    【讨论】:

      【解决方案2】:

      您应该使用 ID 开头,例如 America/New_York

      问题在于“东部标准时间”和“东部夏令时间”映射到相同的 id。

      此外,这些是显示名称的英文形式。法国的用户可能会使用Europe/Paris 区域,而在英语中我们会使用“中欧标准时间”或“中欧夏令时间”的显示名称。但在法语中,他们会使用“heure normale de l’Europe centrale”或“heure avancée d’Europe centrale”的显示名称。 Unicode CLDR 有这些翻译。我不确定 Android 使用它们的程度。

      此外,当您说“中部标准时间”之类的内容时 - 这不一定是唯一的。您可能正在谈论America/Chicago,或者您可能正在谈论America/Costa_Rica。哎呀,您可能在谈论Australia/Adelaide,虽然有些人可能会称其为“澳大利亚中部标准时间”,但这与称我们的“美国中部标准时间”大致相同。

      所以... 显示显示名称,但存储 ID。抓住 ID 并使用它 - 不要试图从显示名称中猜测它。

      【讨论】:

        猜你喜欢
        • 2021-07-14
        • 2016-09-25
        • 2017-12-01
        • 1970-01-01
        • 2020-06-09
        • 2015-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多