Created
June 1, 2023 15:16
-
-
Save mayanksdudakiya/fc734ef6ee9a76e0e94db52ba4f3296c to your computer and use it in GitHub Desktop.
Dynamically generate lists of Timezones in PHP/Laravel/WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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