Easily Create a Timezone List with PHP

Sometimes, you want to create a list of available time zones to prompt your user to select his/her time zone. Fortunately, PHP offers timezone_identifiers_list (PHP 5 >= 5.2.0). You can create your list easily, using a function like this

<?php
/**
 * Timezones list with GMT offset
 *
 * @return array
 * @link http://stackoverflow.com/a/9328760
 */
function tz_list() {
        $zones_array = array();
        $timestamp = time();
        foreach(timezone_identifiers_list() as $key => $zone) {
                date_default_timezone_set($zone);
                $zones_array[$key]['zone'] = $zone;
                $zones_array[$key]['diff_from_GMT'] = 'UTC/GMT ' . date('P', $timestamp);
        }
        return $zones_array;
}
?>

The above function returns an array with all timezones and the GMT offset for each timezone.

Example

A simple example:

<div style="margin-top: 20px;">
        <select style="font-family: 'Courier New', Courier, monospace; width: 450px;">
                <option value="0">Please, select timezone</option>
                <?php foreach(tz_list() as $t) { ?>
                        <option value="<?php print $t['zone'] ?>">
                                <?php print $t['diff_from_GMT'] . ' - ' . $t['zone'] ?>
                        </option>
                <?php } ?>
        </select>
</div>

References

From PHP manual

Your comments are welcome!


Never Miss A Post!

Subscribe to our free NewsLetter