Getting ZoneId from a SimpleTimeZone

前端 未结 3 861
無奈伤痛
無奈伤痛 2020-12-12 06:36

Using Java I have a SimpleTimeZone instance with GMT offset and daylight saving time information from a legacy system.

I would like to retrieve Zo

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 06:57

    I don’t think this is possible. One may also ask what sense it would make. If a time zone is not in the Olson database, it is hardly used in the real world, so what good use could it have in your program? I understand, of course, the case where your legacy program creates a SimpleTimeZone that does represent a time zone used in the wild, but just gives it an incorrect ID so that TimeZone.toZoneId() cannot make the correct translation.

    I checked the source code of TimeZone.toZoneId(). It relies solely on the value obtained from the getID method. It does not look at offset or zone rules. And importantly, SimpleTimeZone does not override the method. So it appears that if your SimpleTimeZone has an known ID (including the frowned-upon abbreviations like EST or ACT), you will get the correct ZoneId. Otherwise you will not.

    So I suppose your best bet is to find out what is the correct time zone ID for the time zone that your legacy code is trying to give you, and then get your ZoneId from ZoneId.of(String). Or slightly nicer, build your own map of aliases containing the ID or IDs from your legacy code and the corresponding modern ID/s, and then use ZoneId.of(String, Map).

    One possible attempt at automating the translation would be to iterate through the available time zones (which you obtain through TimeZone.getAvailableIDs() and TImeZone.getTimeZone(String)) and compare with each using hasSameRules(). Then create your ZoneId from the ID string or the TimeZone obtained from it.

    Sorry, this was not the answer you were hoping for.

提交回复
热议问题