I have a string, I need to check whether it is a standard time zone identifier or not. I am not sure which method I need to use.
String timeZoneToCheck = "UTC";
I would like to check whether it represents a valid time zone or not.
I have a string, I need to check whether it is a standard time zone identifier or not. I am not sure which method I need to use.
String timeZoneToCheck = "UTC";
I would like to check whether it represents a valid time zone or not.
Since
TimeZone#getTimeZone(String id)
returns a default if the value is invalid (rather than returning an invalid time zone), if the reinterpreted value does not match the initial value, it wasn't valid.You can use
TimeZone.getAvailableIDs()
to get list of supported IdThis is a more efficient solution, than looping through all possible IDs. It checks the output of
getTimeZone
.Java Docs (TimeZone#getTimeZone):
So if the output is the GMT timezone the input is invalid, except if the input accually was "GMT".
Or if you want to use the valid timezone without calling getTimeZone twice:
The method returns true for the following:
...And false with the following timezones:
You can get all supported ID using getAvailableIDs()
Then loop the supportedID array and compare with your String.
Example:
You can write it in one line