有没有一种方法可以通过用户的纬度和经度获取他们所在的时区?不仅仅是偏移量,而是他们实际所在的时区。
本质上来说,我正在寻找DateTimeZone :: getLocation的相反极点,它返回某个时区的纬度和经度。
有没有一种方法可以通过用户的纬度和经度获取他们所在的时区?不仅仅是偏移量,而是他们实际所在的时区。
本质上来说,我正在寻找DateTimeZone :: getLocation的相反极点,它返回某个时区的纬度和经度。
对于那些想要从国家代码、纬度和经度获取时区的人。(如果您的服务器上安装了geoip模块,则很容易获得它)
试试这个,我添加了一个距离计算 - 仅适用于具有多个时区的国家。哦,国家代码是两个字母的ISO代码。
// ben@jp
function get_nearest_timezone($cur_lat, $cur_long, $country_code = '') {
$timezone_ids = ($country_code) ? DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $country_code)
: DateTimeZone::listIdentifiers();
if($timezone_ids && is_array($timezone_ids) && isset($timezone_ids[0])) {
$time_zone = '';
$tz_distance = 0;
//only one identifier?
if (count($timezone_ids) == 1) {
$time_zone = $timezone_ids[0];
} else {
foreach($timezone_ids as $timezone_id) {
$timezone = new DateTimeZone($timezone_id);
$location = $timezone->getLocation();
$tz_lat = $location['latitude'];
$tz_long = $location['longitude'];
$theta = $cur_long - $tz_long;
$distance = (sin(deg2rad($cur_lat)) * sin(deg2rad($tz_lat)))
+ (cos(deg2rad($cur_lat)) * cos(deg2rad($tz_lat)) * cos(deg2rad($theta)));
$distance = acos($distance);
$distance = abs(rad2deg($distance));
// echo '<br />'.$timezone_id.' '.$distance;
if (!$time_zone || $tz_distance > $distance) {
$time_zone = $timezone_id;
$tz_distance = $distance;
}
}
}
return $time_zone;
}
return 'unknown';
}
//timezone for one NY co-ordinate
echo get_nearest_timezone(40.772222,-74.164581) ;
// more faster and accurate if you can pass the country code
echo get_nearest_timezone(40.772222, -74.164581, 'US') ;
纬度
和经度
,并返回如下的数组:array(
'dstOffset' => (int) 3600,
'rawOffset' => (int) -18000,
'status' => 'OK',
'timeZoneId' => 'America/New_York',
'timeZoneName' => 'Eastern Daylight Time'
)
...但是有一些限制:
[2019年更新] Google时区API已经设置了使用限制。基本上,您的项目必须启用计费,但每个月会应用200美元的“Google Maps平台信用额度”(因此在大多数情况下,您的前40,000个时区API调用/月将免费)。
如何找到最接近所有时区位置列表中的点?我想知道这有多准确?
更新: 最终,我想出了这个适合我的代码片段。这对于所有位置都可以正常工作,但对于靠近边界的位置可能不太准确。
/**
* Attempts to find the closest timezone by coordinates
*
* @static
* @param $lat
* @param $lng
*/
public static function getClosestTimezone($lat, $lng)
{
$diffs = array();
foreach(DateTimeZone::listIdentifiers() as $timezoneID) {
$timezone = new DateTimeZone($timezoneID);
$location = $timezone->getLocation();
$tLat = $location['latitude'];
$tLng = $location['longitude'];
$diffLat = abs($lat - $tLat);
$diffLng = abs($lng - $tLng);
$diff = $diffLat + $diffLng;
$diffs[$timezoneID] = $diff;
}
//asort($diffs);
$timezone = array_keys($diffs, min($diffs));
return $timezone[0];
}