Java: convert Europe / London to a 3-digit time zone

How to convert timezone identifiers to the corresponding three-digit string? For example, "Europe / London" => "GMT"

+3
source share
2 answers

See method String getDisplayName(boolean daylight,int style)c java.util.TimeZone. The style can be TimeZone.LONGeither TimeZone.SHORTa short style that returns the short name of the time zone.


A longer approach is to verify the output String[] TimeZone.getAvailableIDs(int offset). Short time zone codes can be ambiguous or redundant, so you might want to learn more about this:

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,
+2
source

, 3- .

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

Source: https://habr.com/ru/post/1731255/


All Articles