Skip to content

Instantly share code, notes, and snippets.

@hotmeteor
Last active February 12, 2023 23:03
Show Gist options
  • Save hotmeteor/5bb615ce3b3851a8f9ae to your computer and use it in GitHub Desktop.
Save hotmeteor/5bb615ce3b3851a8f9ae to your computer and use it in GitHub Desktop.
[PHP] Generate a timezone list with optgroups
/**
* 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