TimeZone validation in Java

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

    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
    }
    

提交回复
热议问题