简体   繁体   中英

Converting displayName string to timezone in Java

I am writing a calendar app in android and have to deal with timezones. One of the server is exchange and returns string like follow:

(UTC-12:00) International Date Line West
(UTC+01:00) Brussels, Copenhagen, Madrid, Paris
...

Could you please advise the best way to convert the string above to a Java TimeZone? The solution I see is to write a mapping table to map to Java timezone IDs or to regexp on the UTC+/-hh:mm pattern.

A simple approach comes to mind: use the timezone as the identifier. This isn't perfect, since it'll give you only a TimeZone with the same timezone. But it's a start.

Something like this:

Pattern pattern = Pattern.compile("UTC([+\-]\d):\d\d");
Matcher tagMatch = pattern.matcher(sourceString);
while (tagMatch.find()) {
    String parsed = parseTag(tagMatch.group(1);
    TimeZone t= TimeZone.getTimeZone(String.format("Etc/GMT%s", parsed));
}

This constructions an ID like Etc/GMT+3 or Etc/GMT-11 , which is valid according to this list .

Ideally, the timezone ID can be something like Europe/Brussels , but it sounds like you don't have enough information to get the full identifier -- only the actual GMT offset.

Standard disclaimer: code may not compile, I didn't test it, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM