Find Closest Timezone ID by Latitude/Longitude Coordinates Using Only PHP

This page is in the Code Graveyard where I lay to rest snippets of code that I don't use anymore. Some have lost their usefulness due to the evolving nature of the web, while others have been replaced with better code. "Be Ye Warned!"

This function gets the closest timezone ID based on latitude/longitude coordinates using only PHP. It doesn’t use any other library, webservice, or API. It only uses the PHP DateTimeZone class.

This function is here only for archival purposes.

You should NOT use this function if you need to get an accurate timezone. Many times, this will give the neighboring time zone instead of the zone for your coordinates. This calculates the shortest distance to the main location of a timezone (DateTimeZone::getLocation). That is, the closest “main location” of a timezone. Many times, this can be the neighboring timezone rather than the one for your coordinates. For example, if you’re searching for a timezone for a city near the outer edge of one timezone, and close to another timezone, this function will many times give the timezone for the neighboring zone, since it’s closer in longitude/latitude to the its “location.” This will be the wrong timezone for your coordinates. You cannot rely on this for accurate timezones.

(However, this does accurately calculate which timezone “location” is the shortest distance away, even if it’s not the accurate timezone for your coordinates.)
)

/**
 * Attempts to find the closest timezone ID by coordinates using only PHP
 * 
 * @param $latitude Latitude decimal
 * @param $longitude Longitude decimal
 * @return string $timezone The time zone identifier, same as IANA/Olson zone name
 * 
 */
function getPHPtimezone($latitude, $longitude) {
    $diffs = array();
    foreach(DateTimeZone::listIdentifiers() as $timezoneID) {
	      $timezone = new DateTimeZone($timezoneID);
	      $location = $timezone->getLocation();
	      $tLat = $location['latitude'];
	      $tLng = $location['longitude'];
	      $diffLat = abs($latitude - $tLat);
	      $diffLng = abs($longitude - $tLng);
	      $diff = $diffLat + $diffLng;
	      $diffs[$timezoneID] = $diff;
    }

    $timezone = array_keys($diffs, min($diffs));
	return $timezone[0];
}

See more: ,

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]