简体   繁体   中英

Parse string description of timezone

I get information about timezone in such string format.

 (UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius

Is it somehow possible to parse it into some TimeZone object in Java with standard library or external one?

Depending how you want to use the TimeZone afterwards you might either create a custom one

String input = "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius";
// assuming the format is always fixed at the beginning
String timeZoneOffset = input.substring(4,10);
TimeZone timeZone = TimeZone.getTimeZone("GMT" + timeZoneOffset);
System.out.println("timeZone = " + timeZone);

output (line wrapped)

timeZone = sun.util.calendar.ZoneInfo[id="GMT+02:00",offset=7200000,dstSavings=0,\
useDaylight=false,transitions=0,lastRule=null]

You might get into trouble related to the daytime savings.

Or you create a lookup map with an entry for each offset (stripped down code snipped)

String input = "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius";
// assuming the format is always fixed at the beginning
String timeZoneOffset = input.substring(4,10);

// needs to be initialized somewhere
Map<String, TimeZone> timeZones = new HashMap<>();
// you need to add all offsets
timeZones.put("+02:00", TimeZone.getTimeZone("EET"));

System.out.println("timeZone lookup = " + timeZones.get(timeZoneOffset));

output (line wrapped)

timeZone lookup = sun.util.calendar.ZoneInfo[id="EET",offset=7200000,dstSavings=3600000,\
useDaylight=true,transitions=123,lastRule=java.util.SimpleTimeZone[id=EET,offset=7200000,\
dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,\
startDay=-,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,\
endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]

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