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\"
This is a more efficient solution, than looping through all possible IDs. It checks the output of getTimeZone
.
Java Docs (TimeZone#getTimeZone):
Returns: the specified TimeZone, or the GMT zone if the given ID cannot be understood.
So if the output is the GMT timezone the input is invalid, except if the input accually was "GMT".
public static boolean isValidTimeZone(@NonNull String timeZoneID) {
return (timeZoneID.equals("GMT") || !TimeZone.getTimeZone(timeZoneID).getID().equals("GMT"));
}
Or if you want to use the valid timezone without calling getTimeZone
twice:
TimeZone timeZone = TimeZone.getTimeZone(timeZoneToCheck);
if(timeZoneToCheck.equals("GMT") || !timeZone.getID().equals("GMT")) {
// TODO Valid - use timeZone
} else {
// TODO Invalid - handle the invalid input
}