How to check is timezone identifier valid from code?

后端 未结 8 1863
无人及你
无人及你 2020-12-05 04:53

I\'ll try to explain what\'s the problem here.

According to list of supported timezones from PHP manual, I can see all valid TZ identifiers in PHP.

My first

8条回答
  •  孤街浪徒
    2020-12-05 05:22

    Why not use @ operator? This code works pretty well, and you don't change default timezone:

    function isValidTimezoneId($timezoneId) {
        @$tz=timezone_open($timezoneId);
        return $tz!==FALSE;
    }
    

    If you don't want @, you can do:

    function isValidTimezoneId($timezoneId) {
        try{
            new DateTimeZone($timezoneId);
        }catch(Exception $e){
            return FALSE;
        }
        return TRUE;
    } 
    

提交回复
热议问题