I often find myself developing applications that need to support users in different timezones, it is important to these users that dates are displayed in their preferred timezone. I thought I would share with you the function I use to create a list of timezones, each with their current UTC offset.
The following function will return a list of timezones ordered by their UTC offset and timezone identifier in ascending order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
/** * Return an array of timezones * * @return array */ function timezoneList() { $timezoneIdentifiers = DateTimeZone::listIdentifiers(); $utcTime = new DateTime('now', new DateTimeZone('UTC')); $tempTimezones = array(); foreach ($timezoneIdentifiers as $timezoneIdentifier) { $currentTimezone = new DateTimeZone($timezoneIdentifier); $tempTimezones[] = array( 'offset' => (int)$currentTimezone->getOffset($utcTime), 'identifier' => $timezoneIdentifier ); } // Sort the array by offset,identifier ascending usort($tempTimezones, function($a, $b) { return ($a['offset'] == $b['offset']) ? strcmp($a['identifier'], $b['identifier']) : $a['offset'] - $b['offset']; }); $timezoneList = array(); foreach ($tempTimezones as $tz) { $sign = ($tz['offset'] > 0) ? '+' : '-'; $offset = gmdate('H:i', abs($tz['offset'])); $timezoneList[$tz['identifier']] = '(UTC ' . $sign . $offset . ') ' . $tz['identifier']; } return $timezoneList; } |
Here is the format of the array which this function returns:
1 2 3 4 5 6 7 8 9 10 |
Array ( [Pacific/Midway] => (UTC -11:00) Pacific/Midway [Pacific/Niue] => (UTC -11:00) Pacific/Niue [Pacific/Pago_Pago] => (UTC -11:00) Pacific/Pago_Pago ... [Pacific/Enderbury] => (UTC +13:00) Pacific/Enderbury [Pacific/Tongatapu] => (UTC +13:00) Pacific/Tongatapu [Pacific/Kiritimati] => (UTC +14:00) Pacific/Kiritimati ) |
You could for example use this to generate an HTML drop down select of timezones using the following code:
1 2 3 4 5 6 |
$timezoneList = timezoneList(); echo '<select name="timezone">'; foreach ($timezoneList as $value => $label) { echo '<option value="' . $value . '">' . $label . '</option>'; } echo '</select>'; |
I hope this comes in handy!