Monday 24 September 2018

Generate a dropdown list of timezones in php

Applications often allow users to select their timezones for reporting the proper time properly. Here is a quick function that can be used to generate a dropdown list of timezones that is easy to read and understand.

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
43
44
45
46
47
48
49
50
51
52
53
54
<?php
 
function get_timezones()
{
    $o = array();
     
    $t_zones = timezone_identifiers_list();
     
    foreach($t_zones as $a)
    {
        $t = '';
         
        try
        {
            //this throws exception for 'US/Pacific-New'
            $zone = new DateTimeZone($a);
             
            $seconds = $zone->getOffset( new DateTime("now" , $zone) );
            $hours = sprintf( "%+02d" , intval($seconds/3600));
            $minutes = sprintf( "%02d" , ($seconds%3600)/60 );
     
            $t = $a ."  [ $hours:$minutes ]" ;
             
            $o[$a] = $t;
        }
         
        //exceptions must be catched, else a blank page
        catch(Exception $e)
        {
            //die("Exception : " . $e->getMessage() . '<br />');
            //what to do in catch ? , nothing just relax
        }
    }
     
    ksort($o);
     
    return $o;
}
 
$o = get_timezones();
?>
 
<html>
<body>
<select name="time_zone">
<?php
    foreach($o as $tz => $label)
    {
        echo "<option value="$tz">$label</option>";
    }
?>
</select>
</body>
</html>

0 comments:

Post a Comment