Last active
October 27, 2024 04:28
-
-
Save hotmeteor/5bb615ce3b3851a8f9ae to your computer and use it in GitHub Desktop.
[PHP] Generate a timezone list with optgroups
This file contains 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
/** | |
* Inspired by http://stackoverflow.com/questions/1727077/generating-a-drop-down-list-of-timezones-with-php | |
* @return array | |
*/ | |
function generate_timezone_list() | |
{ | |
static $regions = [ | |
'Africa' => DateTimeZone::AFRICA, | |
'Americas' => DateTimeZone::AMERICA, | |
// 'Antartica' => DateTimeZone::ANTARCTICA, | |
'Asia' => DateTimeZone::ASIA, | |
'Atlantic' => DateTimeZone::ATLANTIC, | |
'Australia' => DateTimeZone::AUSTRALIA, | |
'Europe' => DateTimeZone::EUROPE, | |
'Indian Ocean' => DateTimeZone::INDIAN, | |
'Pacific' => DateTimeZone::PACIFIC, | |
]; | |
$region_list = []; | |
foreach ($regions as $name => $region) { | |
$region_list[$name] = DateTimeZone::listIdentifiers($region); | |
} | |
$timezone_offsets = []; | |
foreach ($region_list as $name => $timezones) { | |
foreach ($timezones as $timezone) { | |
$tz = new DateTimeZone($timezone); | |
$timezone_offsets[$name][$timezone] = $tz->getOffset(new DateTime); | |
} | |
asort($timezone_offsets[$name]); | |
} | |
// sort timezone by offset | |
$timezone_list = array(); | |
foreach ($timezone_offsets as $name => $timezones) { | |
foreach ($timezones as $timezone => $offset) { | |
$offset_prefix = $offset < 0 ? '-' : '+'; | |
$offset_formatted = gmdate('H:i', abs($offset)); | |
$pretty_offset = "UTC${offset_prefix}${offset_formatted}"; | |
$timezone_list[$name][$timezone] = "(${pretty_offset}) $timezone"; | |
} | |
} | |
return $timezone_list; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment