TimeZone validation in Java

前端 未结 9 2276
梦如初夏
梦如初夏 2021-02-20 00:08

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\"         


        
9条回答
  •  悲&欢浪女
    2021-02-20 00:28

    If TimeZone.getAvailableIDs() contains ID in question, it's valid:

    public boolean validTimeZone(String id) {
        for (String tzId : TimeZone.getAvailableIDs()) {
                if (tzId.equals(id))
                    return true;
        }
        return false;
    }
    

    Unfortunately TimeZone.getTimeZone() method silently discards invalid IDs and returns GMT instead:

    Returns:

    the specified TimeZone, or the GMT zone if the given ID cannot be understood.

提交回复
热议问题