Ozzie Neher

Developing for the Web

Friendly Timezones in PHP

January 2nd, 2017

Have you ever seen an intimidating dropdown like the one below when asked to select your timezone on a website?

PHP Timezone Dropdown

We recently had this problem in our office, so I created this package to solve that problem! The "user friendly names" are taken from Microsoft's Timezone Index Values and are mapped to the appropriate PHP timezone names. The package handles Daylight Savings Time as well by calculating all of the offsets when they are requested.

You can view the source code on GitHub and install it via Packagist/Composer.

You can install the package via

composer require nehero/friendlytimezone

Using it in PHP:

// autoload / require_once the file here
require_once __DIR__ . '/vendor/autoload.php';

// If you want for dependency injection / OO
// use Nehero\FriendlyTimezone;

// But it's easiest to use statically
use Nehero\FriendlyTimezone\Facade as FriendlyTimezone;

// If no options are passed to get(), values are sorted by `asc` GMT offset value
$timezones = FriendlyTimezone::get();

// You can also optionally pass an array of options
// ex.
$timezones = FriendlyTimezone::get([ 'order' => 'desc' ]);
$timezones = FriendlyTimezone::get([ 'order' => 'asc' ]);

And then in your view:

<select name="timezones">
    <?php foreach($timezones as $label => $value): ?>
        <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
    <?php endforeach; ?>
</select>

Easy as that. If you see an issue or think a zone could be mapped better, please open an issue or a pull request!