开发者

Java: Convert "Europe/London" to 3 digit timezone

How can I conve开发者_StackOverflow中文版rt the timezone identifiers to the corresponding 3 digit string? For example "Europe/London" => "GMT"


See the String getDisplayName(boolean daylight,int style) method in java.util.TimeZone. The style may be TimeZone.LONG or TimeZone.SHORT with the short style returning the short name of the time zone.


A more long winded approach is to check the output of String[] TimeZone.getAvailableIDs(int offset). The short time zone codes can be ambiguous or redundant, so maybe you might want to be more thorough about it:

TimeZone tz = TimeZone.getTimeZone("Europe/London");
for (String s : TimeZone.getAvailableIDs(tz.getOffset(System.currentTimeMillis()))) {
    System.out.print(s + ",");
}

------------------------------------------------------

Africa/Abidjan,Africa/Accra,Africa/Bamako,Africa/Banjul,Africa/Bissau,
Africa/Casablanca,Africa/Conakry,Africa/Dakar,Africa/El_Aaiun,Africa/Freetown,
Africa/Lome,Africa/Monrovia,Africa/Nouakchott,Africa/Ouagadougou,Africa/Sao_Tome,
Africa/Timbuktu,America/Danmarkshavn,Atlantic/Canary,Atlantic/Faeroe,
Atlantic/Faroe,Atlantic/Madeira,Atlantic/Reykjavik,Atlantic/St_Helena,
Eire,Etc/GMT,Etc/GMT+0,Etc/GMT-0,Etc/GMT0,Etc/Greenwich,Etc/UCT,
Etc/UTC,Etc/Universal,Etc/Zulu,Europe/Belfast,
Europe/Dublin,Europe/Guernsey,Europe/Isle_of_Man,Europe/Jersey,Europe/Lisbon,
Europe/London,GB,GB-Eire,GMT,GMT0,Greenwich,Iceland,Portugal,UCT,UTC,
Universal,WET,Zulu,


You can use following code to find 3 digit abbreviation for any timezone.

Date date = new Date(); 

String TimeZoneIds[] = TimeZone.getAvailableIDs();

String timezoneShortName = "";

String timezoneLongName  = "Europe/London";

for (int i = 0; i < TimeZoneIds.length; i++) {
    TimeZone tz = TimeZone.getTimeZone(TimeZoneIds[i]);
    String tzName = tz.getDisplayName(tz.inDaylightTime(date),TimeZone.SHORT);

    if(timezoneLongName.equals(TimeZoneIds[i])){
        timezoneShortName = tzName;
        break;
    }
}
System.out.println(timezoneShortName);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜