Skip to content

Instantly share code, notes, and snippets.

@ve3
Last active Nov 17, 2019
Embed
What would you like to do?
Generate timezones list array
<?php
function getTimezones(): array
{
$timezones = \DateTimeZone::listIdentifiers();
$options = [];
$lastRegion = '';
if (is_array($timezones)) {
foreach ($timezones as $key => $timezone) {
$DateTimeZone = new \DateTimeZone($timezone);
$expTimezone = explode('/', $timezone);
if (isset($expTimezone[0])) {
if ($expTimezone[0] !== $lastRegion) {
$lastRegion = $expTimezone[0];
}
$getOffset = $DateTimeZone->getOffset(new \DateTime());
$offset = ($getOffset < 0 ? '-' : '+');
$offset .= gmdate('H:i', abs($getOffset));
$options[$expTimezone[0]][$timezone] = [
'name' => $timezone,
'offset' => $offset,
];
unset($getOffset, $offset);
}
unset($DateTimeZone, $expTimezone);
}// endforeach;
unset($key, $timezone);
}
unset($lastRegion, $timezones);
return $options;
}
$options = getTimezones();
if (is_array($options)) {
echo '<select name="timezone">' . PHP_EOL;
foreach ($options as $optgroup => $items) {
echo ' <optgroup label="' . $optgroup . '">' . PHP_EOL;
if (is_array($items)) {
foreach ($items as $key => $item) {
echo ' <option value="' . $key . '">';
echo $item['name'] . ' (UTC ' . $item['offset'] . ')';
echo '</option>' . PHP_EOL;
}// endforeach;
unset($item, $key);
}
echo ' </optgroup>' . PHP_EOL;
}// endforeach;
unset($items, $optgroup);
echo '</select>' . PHP_EOL;
}
unset($options);
/*
<select name="timezone">
<optgroup label="Africa">
<option value="Africa/Abidjan">Africa/Abidjan (UTC +00:00)</option>
<option value="Africa/Accra">Africa/Accra (UTC +00:00)</option>
...
</optgroup>
</select>
*/
<?php
$timezones = \DateTimeZone::listIdentifiers();
$options = [];
$lastRegion = '';
if (is_array($timezones)) {
foreach ($timezones as $key => $timezone) {
$DateTimeZone = new \DateTimeZone($timezone);
$expTimezone = explode('/', $timezone);
if (isset($expTimezone[0])) {
if ($expTimezone[0] !== $lastRegion) {
$lastRegion = $expTimezone[0];
}
$getOffset = $DateTimeZone->getOffset(new \DateTime());
$offset = ($getOffset < 0 ? '-' : '+');
$offset .= gmdate('H:i', abs($getOffset));
$options[$expTimezone[0]][$timezone] = [
'name' => $timezone,
'offset' => $offset,
];
unset($getOffset, $offset);
}
unset($DateTimeZone, $expTimezone);
}// endforeach;
unset($key, $timezone);
}
unset($lastRegion, $timezones);
print_r($options);
/*
Array
(
[Africa] => Array
(
[Africa/Abidjan] => Array
(
[name] => Africa/Abidjan
[offset] => +00:00
)
[Africa/Accra] => Array
(
[name] => Africa/Accra
[offset] => +00:00
)
...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment