Monday, March 14, 2011

How to select the timezone using php

In PHP we can find the server time using the date(). But it returns the time of the server where it located. If our website users are from different country we need to display the correct country time instead of server time. If we want to display the local time of a users browsing your webpage, we must find the timezone of the user. If we know the timezone we can find the time of the user timezone. We can list the timezones in a select box and if the user selects the timezone we can find the time of the timezone. In this example it shows how to get the user timezone times.

Step 1 : List the timezones
The 'DateTimeZone::listIdentifiers() ' function returns the timezones and we can iterate the timezones.
To get the timezones use the following code
<select id="timezone" name="timezone">
<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
foreach( $timezone_identifiers as $value ){
if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) ){
$ex=explode("/",$value);//obtain continent,city
if ($continent!=$ex[0]){
if ($continent!="") echo '</optgroup>';
echo '<optgroup label="'.$ex[0].'">';
}
$city=$ex[1];
$continent=$ex[0];
echo '<option value="'.$value.'">'.$city.'</option>';
$selected = '';
}
}
?>
</optgroup>
</select>

The above code will display the timezones in a select box. The user can select the corresponding timezone. It displays the timezones in the basis of continent. Each continental city is listed as groups.

Step 2: Submit the data and set the timezone

use <form> to submit the selected timezone and set the selected timezone as default timezone. use 'date_default_timezone_set' to set the timezone and get the time using time(). Now it will return the time of the new timezone.
<?php
date_default_timezone_set("$timezone"); // set the selected time zone
echo "<pre>";
print_r( getdate() );
?>
Now it will print the current date and time of the selected timezone.


Full Source Code
<?php
extract($_POST);
date_default_timezone_set("$timezone");
echo "Time details";
echo "<pre>";
print_r( getdate() );
echo "<pre>";
echo "Current Time : ";
echo date("H:i:s");
echo "<br>";
echo "Current Time Zone name : ";
echo $timezone;
?>
<form method="post">
<select id="timezone" name="timezone">
<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
foreach( $timezone_identifiers as $value ){
if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) ){
$ex=explode("/",$value);//obtain continent,city
if ($continent!=$ex[0]){
if ($continent!="") echo '</optgroup>';
echo '<optgroup label="'.$ex[0].'">';
}

$city=$ex[1];
$continent=$ex[0];
if($value == $timezone)
$selected = 'selected';
echo '<option '.$selected.' value="'.$value.'">'.$city.'</option>';
$selected = '';
}
}
?>
</optgroup>
</select>
<input type="submit">
</form>

No comments:

Post a Comment