Get list of all supported TimeZones and offsets in PHP
October 20, 2017
Dealing with multiple timezones for users is a problem that is (for starters) best addressed by using UTC time with an offset of 0 as the server time. The next part of the problem is how to get a sane list of zones for your user to select from that you know your server supports. You could copy/paste a list, or deal with large clunky classes in frameworks — or, you could use very little code that produces a json encoded object containing all the information about each supported timezone that is required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php // tell browser the content type is json consumable header('Content-Type: application/json'); // set the default timezone to UTC for this script. date_default_timezone_set( "UTC" ); // define variable(s) $zones = array(); // loop through timezones foreach( timezone_identifiers_list() as $zone ) { // set default continent and city $parts = array( '*', $zone ); // if zone is in a continent, set the values to $parts if(strpos( $zone, '/' ) == true) { $parts = explode( '/', $zone ); } // calculate offset based on the default timezone $offset = timezone_offset_get( new DateTimeZone( $zone ), new DateTime() ); // get country, gps coords, etc $location = timezone_location_get( new DateTimeZone( $zone ) ); // short iso letters for zone ( eg: PDT or EST ) $abbr = (new DateTime( "now", new DateTimeZone( $zone ) ))->format('T'); // add the zone information to the collection $zones[$parts[0]][$parts[1]] = array( 'zone' => $zone, 'offset' => $offset, 'location' => $location, 'abbr' => $abbr ); } // output result echo json_encode($zones); |