Get PHP Timezone Name from Latitude and Longitude? [duplicate]
For those who wants to get timezone from country code, latitude and longitude. ( easy to get it if you have a geoip module installed on your server )
Try this, I've added a distance calculation - only for those countries which has multiple timezones.Ah, and the country code is a two letter ISO code.
// ben@jpfunction 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-ordinateecho 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') ;
A good resource is the Google Time Zone API.
Documentation: https://developers.google.com/maps/documentation/timezone/
It takes latitude
and longitude
and returns array like this:
array( 'dstOffset' => (int) 3600, 'rawOffset' => (int) -18000, 'status' => 'OK', 'timeZoneId' => 'America/New_York', 'timeZoneName' => 'Eastern Daylight Time')
...but there are some limits:
[updated 2019] The Google Time Zone API has usage limits in place. Basically, billing must be enabled on your project, but a $200 USD "Google Maps Platform credit" is applied each month (so in most cases your first 40,000 Time Zone API calls/month would be free of charge).