0

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

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

4

2 回答 2

2

您可以使用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
于 2013-09-17T16:42:35.010 回答
0

您应该使用 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 并使用它 - 不要试图从显示名称中猜测它。

于 2013-09-17T17:47:56.320 回答