Skip to content

Instantly share code, notes, and snippets.

@Akimkin
Last active December 8, 2022 08:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akimkin/aa39f74a37434070e58a9749c718554b to your computer and use it in GitHub Desktop.
Save Akimkin/aa39f74a37434070e58a9749c718554b to your computer and use it in GitHub Desktop.
Get list of timezones translated to given language in PHP
<?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