0

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?

4
  • 5
    You could possibly parse the id out of this string and get a new TimeZone object from it. But it seems like an XY problem: why do you get a string like that anyway, and why can't you use the original object or a serialization of it or an easier to parse string? Commented Jun 29, 2017 at 7:14
  • I've decided to use the "id" value of the original timezone object instead of this string. Thanks! Commented Jun 29, 2017 at 8:15
  • 1
    FYI, TimeZone is one of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes. See the classes ZoneId and ZoneOffset. Commented Jun 29, 2017 at 8:22
  • Agree with @BasilBourque. If you got the ID string (either from parsing or some other way), use ZoneId.of(idString). Still easier if you got the original TimeZone object: timeZoneObject.toZoneId(). Commented Jun 29, 2017 at 12:45

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

I will stick to using the original TimeZone object instead of this String. This seems to add unnecessary complexity. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.