Skip to content

Instantly share code, notes, and snippets.

@vrdriver
Forked from xeoncross/timezone.php
Last active January 7, 2018 12:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrdriver/659562a150ba955063ad849e44dac2cc to your computer and use it in GitHub Desktop.
Save vrdriver/659562a150ba955063ad849e44dac2cc to your computer and use it in GitHub Desktop.
The perfect TimeZone selectbox list for PHP 5.3+
<?php
$regions = array(
'Africa' => DateTimeZone::AFRICA,
'America' => DateTimeZone::AMERICA,
'Antarctica' => DateTimeZone::ANTARCTICA,
'Asia' => DateTimeZone::ASIA,
'Atlantic' => DateTimeZone::ATLANTIC,
'Australia' => DateTimeZone::AUSTRALIA,
'Europe' => DateTimeZone::EUROPE,
'Indian' => DateTimeZone::INDIAN,
'Pacific' => DateTimeZone::PACIFIC
);
$timezones = array();
foreach ($regions as $name => $mask)
{
$zones = DateTimeZone::listIdentifiers($mask);
foreach($zones as $timezone)
{
// Lets sample the time there right now
$time = new DateTime(NULL, new DateTimeZone($timezone));
// Us dumb Americans can't handle millitary time
$ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
// Remove region name and add a sample time
$timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
}
}
// View
echo '<label>Select Your Timezone</label>';
echo '<select name="timezone">';
foreach($timezones as $region => $list)
{
echo '<optgroup label="' . $region . '">' . "\n";
foreach($list as $timezone => $name)
{
if($user_timezone_db_entry == $timezone)
{
echo '<option SELECTED value="' . $timezone . '">' . $name . '</option>' . "\n";
}
else
{
echo '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
}
}
echo '<optgroup>' . "\n";
}
echo '</select>';
@vrdriver
Copy link
Author

This has been updated to include Australia, and fix the Asia spelling mistake.

@vrdriver
Copy link
Author

Also fixed it so you can get the name of the text to be stored easily (and received) when using a database.

@vrdriver
Copy link
Author

You'll see on line 43 "$user_timezone_db_entry".
Get this value from your DB if you are storing the TZs as a text value.
Of course, if you are using INT for the TZ and they are all stored in a separate table, then this example won't work for you.

@AtlasApollo
Copy link

A millions thanks, this is awesome and I'll apply it! <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment