Reputation: 658
Is there a way to convert a human-readable timezone string like Eastern Standard Time
to a timezone ID without hard-coding?
If I get the timezone ID then I can set the timezone accordingly.
Upvotes: 0
Views: 1851
Reputation: 24266
You can use the TimeZone class to enumerate the timezone IDs and strings. You can also set a TimeZone from a string value.
The TimeZone class and Locale class can be used to find the appropriate timezone name in the current or some designated timezone. E.g., this code fragment
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>");
}
lists the following names for some European timezones:
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
Upvotes: 2
Reputation: 241603
You should be using the ID to begin with, such as America/New_York
.
The problem is that both "Eastern Standard Time" and "Eastern Daylight Time" would both map to the same id.
Also, those are English forms of the display names. A user in France might use the Europe/Paris
zone, and in English we would use a display name of "Central European Standard Time" or "Central European Summer Time". But in French they would use a display name of "heure normale de l’Europe centrale" or "heure avancée d’Europe centrale". The Unicode CLDR has these translations. I am uncertain as to the degree that Android uses them.
Also, when you say something like "Central Standard Time" - that isn't necessarily unique. You might be talking about America/Chicago
, or you might be talking about America/Costa_Rica
. Heck, you might be talking about Australia/Adelaide
, although some might call that "Australian Central Standard Time", but that's about the same as calling ours "American Central Standard Time".
So... Show the display name, but store the ID. Hold on to the ID and use it - don't try to guess it from the display name.
Upvotes: 0