TimeZone validation in Java

2019-04-22 17:14发布

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.

8条回答
爷的心禁止访问
2楼-- · 2019-04-22 18:07

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.

查看更多
做自己的国王
3楼-- · 2019-04-22 18:07

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.

查看更多
登录 后发表回答