TimeZone validation in Java

前端 未结 9 2216
梦如初夏
梦如初夏 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:26

    I would like to propose the next workaround:

    public static final String GMT_ID = "GMT";
    public static TimeZone getTimeZone(String ID) {
        if (null == ID) {
            return null;
        }
    
        TimeZone tz = TimeZone.getTimeZone(ID);
    
        // not nullable value - look at implementation of TimeZone.getTimeZone
        String tzID = tz.getID();
    
        // check if not fallback result 
        return GMT_ID.equals(tzID) && !tzID.equals(ID) ? null : tz;
    }
    

    As result in case of invalid timezone ID or invalid just custom timezone you will receive null. Additionally you can introduce corresponding null value handler (use case dependent) - throw exception & etc.

提交回复
热议问题