Generating a drop down list of timezones with PHP
Following user210179's example above, I've written the following function to generate me a list of all timezones with their offsets:
function generate_timezone_list()
{
static $regions = array(
DateTimeZone::AFRICA,
DateTimeZone::AMERICA,
DateTimeZone::ANTARCTICA,
DateTimeZone::ASIA,
DateTimeZone::ATLANTIC,
DateTimeZone::AUSTRALIA,
DateTimeZone::EUROPE,
DateTimeZone::INDIAN,
DateTimeZone::PACIFIC,
);
$timezones = array();
foreach( $regions as $region )
{
$timezones = array_merge( $timezones, DateTimeZone::listIdentifiers( $region ) );
}
$timezone_offsets = array();
foreach( $timezones as $timezone )
{
$tz = new DateTimeZone($timezone);
$timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
}
// sort timezone by offset
asort($timezone_offsets);
$timezone_list = array();
foreach( $timezone_offsets as $timezone => $offset )
{
$offset_prefix = $offset < 0 ? '-' : '+';
$offset_formatted = gmdate( 'H:i', abs($offset) );
$pretty_offset = "UTC${offset_prefix}${offset_formatted}";
$timezone_list[$timezone] = "(${pretty_offset}) $timezone";
}
return $timezone_list;
}
This will generate an array looking like:
[Pacific/Midway] => (UTC-11:00) Pacific/Midway
[Pacific/Pago_Pago] => (UTC-11:00) Pacific/Pago_Pago
[Pacific/Niue] => (UTC-11:00) Pacific/Niue
[Pacific/Honolulu] => (UTC-10:00) Pacific/Honolulu
[Pacific/Fakaofo] => (UTC-10:00) Pacific/Fakaofo
…
It's currently sorted by offsets, but you can easily sort by the timezone name by doing a ksort()
instead of asort()
.
I would do it in PHP, except I would avoid doing preg_match 100 some times and do this to generate your list.
$tzlist = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
Also, I would use PHP's names for the 'timezones' and forget about GMT offsets, which will change based on DST. Code like that in phpbb is only that way b/c they are still supporting PHP4 and can't rely on the DateTime or DateTimeZone objects being there.