In PHP, how can I get Timezone from offset and country?

╄→尐↘猪︶ㄣ 提交于 2019-12-19 04:18:11

问题


I am doing an IP lookup to determine a "best guess" for timezone offset from UTC and the country/region information.

So, for instance, I have offset -3 and country Brazil.

I want to show BRT instead of a random timezone in that same offset, i.e. ART

Is there some built-in way in PHP to be able to set the appropriate timezone with this information?

If not, what would be the easiest way to do this? (Assume that I can't make any outside API calls)

If I do my own database table, how do I ensure it stays up to date?

Thanks!


回答1:


You don't have to roll your own database, here's one from GeoNames. You can also get all the timezone information from PHP.




回答2:


You cannot resolve a timezone from an offset, or even an offset plus country. See the TimeZone != Offset section of the TimeZone tag wiki. The offsets have changed at many points in time, and they will inevitably change again.

You need more information, such as latitude/longitude. See this community wiki.

If you can ask your user for their timezone, please do. That's the best way. My favorite UI for this is a JavaScript map-based timezone picker, such as this one. You can make a best-guess default choice using jsTimeZoneDetect.




回答3:


This PHP function give back an array of all existing Timezones including Offset, not exactly what you are looking for but maybe it helps:

function time_zonelist(){
    $return = array();
    $timezone_identifiers_list = timezone_identifiers_list();
    foreach($timezone_identifiers_list as $timezone_identifier){
        $date_time_zone = new DateTimeZone($timezone_identifier);
        $date_time = new DateTime('now', $date_time_zone);
        $hours = floor($date_time_zone->getOffset($date_time) / 3600);
        $mins = floor(($date_time_zone->getOffset($date_time) - ($hours*3600)) / 60);
        $hours = 'GMT' . ($hours < 0 ? $hours : '+'.$hours);
        $mins = ($mins > 0 ? $mins : '0'.$mins);
        $text = str_replace("_"," ",$timezone_identifier);
        $return[$timezone_identifier] = $text.' ('.$hours.':'.$mins.')';
    }
    return $return;
}


来源:https://stackoverflow.com/questions/14589678/in-php-how-can-i-get-timezone-from-offset-and-country

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!