Skip to content

Instantly share code, notes, and snippets.

@jacurtis
Created October 11, 2017 22:20
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 jacurtis/779da5f7c13046d1c6e8f43db7ff45f7 to your computer and use it in GitHub Desktop.
Save jacurtis/779da5f7c13046d1c6e8f43db7ff45f7 to your computer and use it in GitHub Desktop.
<?php
if (!function_exists('timezoneArray')) {
/**
* description
*
* @param
* @return
*/
function timezoneArray($regions = ["africa", "america", "antarctica", "asia", "atlantic", "australia", "europe", "indian", "pacific"], $detailed = true)
{
static $zones = [];
foreach ($regions as $region) {
if (strtoupper($region) == "AFRICA") {
array_push($zones, DateTimeZone::AFRICA);
} else if (strtoupper($region) == "AMERICA") {
array_push($zones, DateTimeZone::AMERICA);
} else if (strtoupper($region) == "ANTARCTICA") {
array_push($zones, DateTimeZone::ANTARCTICA);
} else if (strtoupper($region) == "ASIA") {
array_push($zones, DateTimeZone::ASIA);
} else if (strtoupper($region) == "ATLANTIC") {
array_push($zones, DateTimeZone::ATLANTIC);
} else if (strtoupper($region) == "AUSTRALIA") {
array_push($zones, DateTimeZone::AUSTRALIA);
} else if (strtoupper($region) == "EUROPE") {
array_push($zones, DateTimeZone::EUROPE);
} else if (strtoupper($region) == "INDIAN") {
array_push($zones, DateTimeZone::INDIAN);
} else if (strtoupper($region) == "PACIFIC") {
array_push($zones, DateTimeZone::PACIFIC);
}
$timezones = array();
foreach( $zones as $zone )
{
$timezones = array_merge( $timezones, DateTimeZone::listIdentifiers( $zone ) );
}
$timezone_offsets = array();
foreach( $timezones as $timezone )
{
$tz = new DateTimeZone($timezone);
$timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
}
// sort timezone by offset
asort($timezone_offsets);
$timezone_list = array();
foreach( $timezone_offsets as $timezone => $offset )
{
$offset_prefix = $offset < 0 ? '-' : '+';
$offset_formatted = gmdate( 'H:i', abs($offset) );
$pretty_offset = "UTC${offset_prefix}${offset_formatted}";
if ($detailed) {
$timezoneFormatted = $timezone;
} else {
$tzFormat = explode('/', $timezone, 2);
$timezoneFormatted = $tzFormat[1];
}
$timezone_list[$timezone] = "(${pretty_offset}) $timezoneFormatted";
}
}
return $timezone_list;
}
}
@jacurtis
Copy link
Author

This generates an array like:

array(
  "America/Denver" => "(UTC - 6:00) America/Denver"
  "America/Phoenix" => "(UTC - 6:00) America/Phoenix"
  ...
);

or if you pass false in the second parameter then you get:

array(
  "America/Denver" => "(UTC - 6:00) Denver"
  "America/Phoenix" => "(UTC - 6:00) Phoenix"
  ...
);

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