Skip to content

Instantly share code, notes, and snippets.

@mayanksdudakiya
Created June 1, 2023 15:16
Show Gist options
  • Select an option

  • Save mayanksdudakiya/fc734ef6ee9a76e0e94db52ba4f3296c to your computer and use it in GitHub Desktop.

Select an option

Save mayanksdudakiya/fc734ef6ee9a76e0e94db52ba4f3296c to your computer and use it in GitHub Desktop.
Dynamically generate lists of Timezones in PHP/Laravel/WordPress
<?php
public function getTimezoneList(): array
{
// Get all timezone
$timezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$findUtcKey = array_search('UTC', $timezones);
unset($timezones[$findUtcKey]);
$timezone_offsets = [];
foreach ($timezones as $timezone) {
$tz = new DateTimeZone($timezone);
$timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
}
// sort timezone by offset
asort($timezone_offsets);
$timezone_list = [];
foreach ($timezone_offsets as $timezone => $offset) {
$offset_prefix = $offset < 0 ? '-' : '+';
$offset_formatted = gmdate('H:i', abs($offset));
$pretty_offset = "UTC{$offset_prefix}{$offset_formatted}";
$timezone_list[$timezone] = "({$pretty_offset}) $timezone";
}
return $timezone_list;
}
?>
// Output will be in following format:
(UTC-07:00) America/Los_Angeles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment