Last active
December 8, 2022 08:46
-
-
Save Akimkin/aa39f74a37434070e58a9749c718554b to your computer and use it in GitHub Desktop.
Get list of timezones translated to given language in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get list of timezones translated in given language | |
* | |
* Requires PHP Intl extension to be present & active in your PHP setup | |
* | |
* @param string $langcode - an ISO 639-1 language code | |
* @return array | |
*/ | |
function getTimezoneList($langcode = 'en') { | |
$regions = array( | |
'AFRICA', 'AMERICA', 'ASIA', | |
'ATLANTIC', 'AUSTRALIA', | |
'EUROPE', 'INDIAN', 'PACIFIC' | |
); | |
/* Filter timezones by region (we don't include Antarctica & UTC here) */ | |
$regcode = array_reduce($regions, function($c, $region) { | |
if ($rv = @constant("DateTimeZone::$region")) { | |
$c |= $rv; | |
} | |
return $c; | |
}, 0); | |
/* Get list of timezone IDs (in form of "Region/City") */ | |
$idlist = DateTimeZone::listIdentifiers($regcode); | |
/* Create an array with zone names in selected language as keys | |
* and timezone IDs as values. This way we filler out locations | |
* that have same timezone names. | |
*/ | |
$buf = array(); | |
foreach ($idlist as $id) { | |
$itz = IntlTimeZone::createTimeZone($id); | |
if (!$itz) { | |
continue; | |
} | |
$k = $itz->getDisplayName(false, 2, $langcode); | |
$buf[$k] = $id; | |
} | |
$buf = array_flip($buf); | |
/* Build a fancy timezone information array */ | |
$tz = array(); | |
foreach ($buf as $id => $v) { | |
$itz = IntlTimeZone::createTimeZone($id); | |
$tz[] = array( | |
// Timezone ID (e.g. "Europe/Zurich") | |
'id' => $id, | |
// Timezone abbreviated name (e.g. "GMT+1") | |
'abbr' => $itz->getDisplayName(false, 1, $langcode), | |
// Timezone name (e.g. "Central European Standard Time") | |
'name' => ucfirst($v), | |
// Timezone's offset from UTC, in milliseconds (e.g. 3600000) | |
'ofs' => $itz->getRawOffset() | |
); | |
} | |
/* Sort return array by UTC offset */ | |
usort($tz, function($a, $b) { | |
return $a['ofs'] - $b['ofs']; | |
}); | |
return $tz; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment