Ezil Kannan
Ezil Kannan

Reputation: 63

Convert java.util.TimeZone String to java.util.TimeZone

Is it possible to convert a java.util.TimeZone String

sun.util.calendar.ZoneInfo[id=\"America/Los_Angeles\",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]

back to java.util.TimeZone object?

Upvotes: 0

Views: 432

Answers (1)

D. Kovács
D. Kovács

Reputation: 1270

Part of Effective Java; Item 10:

Provide programmatic information to all the information provided by toString, or clients may try to parse the string to retrieve it.

In other words: if it is doable, don't try to parse the output of toString. If you are forced to do it (but only if really-really-really there is no other way), then you could do it:

  • you have to do it with reflection (TimeZone is an abstract class, in the toString output you see that this instance is not a ZoneInfo but a SimpleTimeZone)
  • you have to parse the data which you need in any of the applicable constructors and invoke it

There is no "easy solution" to "backmapping" a toString representation of TimeZone into a TimeZone object. (There are some APIs where you have a fromString method or similar, the new Java Date API is not one of them, and it shouldn't be).

Upvotes: 1

Related Questions