Is there a way get the timezone of a user by their latitude and longitude? And not just the offset, but the actual timezone they're in.
Essentially, I'm searching for the polar opposite of DateTimeZone::getLocation which returns the latitude and longitude for a certain timezone.
Here's how longitude converts into your personal time zone: 15 degrees of longitude = 1 hour difference; 1 degree longitude = 4 minutes difference. 15 minutes of longitude = 1 minute difference; 1 minute of longitude = 4 seconds difference.
The date_default_timezone_get() function returns the default timezone used by all date/time functions in the script.
Pass latitude and longitude in getaddress() function. It will return address string on success otherwise return boolean false. <? php $lat= 26.754347; //latitude $lng= 81.001640; //longitude $address= getaddress($lat,$lng); if($address) { echo $address; } else { echo "Not found"; } ?>
To find the time zone in hours of a particular location, you can take the longitude -- in degrees -- and divide it by 15. So, for example, 75° E would be 75/15 which equals 5. That translates to the time zone being 5 hours ahead of UTC or GMT time, which can also be labeled as UTC+5.
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@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') ;
Geonames should do the job nicely:
http://www.geonames.org/
They've also got a php library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With