Jump to content

how to create timezone select menu using PHP


Go to solution Solved by Barand,

Recommended Posts

  • Solution

perhaps

$arr = timezone_identifiers_list();

foreach ($arr as $tz) {
    if (strpos($tz, '/')===false ) continue;
    list ($region, $city) = explode('/', $tz, 2);
    $d = new DateTimeZone($tz);
    $secs = $d->getOffset(new DateTime());
    $offset = number_format($secs/3600, 2);
    $tzArray[$offset][$region][] = $city;
}

ksort($tzArray);

$menu = "<option value=''>- select timezone -</option>\n";
foreach ($tzArray as $o => $regzones) {
    $menu .= sprintf("<optgroup label='GMT %+0.2f'>\n", $o);
    ksort($regzones);
    foreach ($regzones as $region => $cities) {
        foreach ($cities as $city)
            $menu .= "<option >$region/$city</option>\n";
    }
    $menu .= "</optgroup>\n";
} 
?>
<select name='tzone'>
    <?=$menu?>
</select>
  • Like 1

Alternative version if you prefer to group the timezones in the menu by region

$arr = timezone_identifiers_list();
$now = new DateTime();

foreach ($arr as $tz) {
    if (strpos($tz, '/')===false ) continue;
    list ($region, $city) = explode('/', $tz, 2);
    $d = new DateTimeZone($tz);
    $secs = $d->getOffset($now);
    $offset = number_format($secs/3600, 2);
    $tzArray[$region][$offset][] = $city;
}

ksort($tzArray);

$menu = "<option value=''>- select timezone -</option>\n";
foreach ($tzArray as $region => $regzones) {
    $menu .= sprintf("<optgroup label='%s'>\n", $region);
    ksort($regzones);
    foreach ($regzones as $o => $cities) {
        foreach ($cities as $city)
            $menu .= sprintf("<option value='$region/$city'>GMT%+0.2f $region/$city</option>\n", $o);
    }
    $menu .= "</optgroup>\n";
} 
?>
<select name='tzone'>
    <?=$menu?>
</select>
  • Like 2
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.