Reputation: 2437
I have a date time entered in the timezone UTC+0 and in the format
$curDate = date("Y-m-d");
$curTime = date("g:i a");
What I want is, detect the timezone of the visiting user.
After that convert the date and time into his/her time zone and show the date time in their timezone.
Upvotes: 0
Views: 1282
Reputation: 491
$utc_date = DateTime::createFromFormat(
'Y-m-d G:i',
'2011-04-27 02:45',
new DateTimeZone('UTC')
);
$acst_date = clone $utc_date; // we don't want PHP's default pass object by reference here
$acst_date->setTimeZone(new DateTimeZone('Australia/Yancowinna'));
echo 'UTC: ' . $utc_date->format('Y-m-d g:i A'); // UTC: 2011-04-27 2:45 AM
echo 'ACST: ' . $acst_date->format('Y-m-d g:i A'); // ACST: 2011-04-27 12:15 PM
Upvotes: 2
Reputation: 1847
Either force the user to provide you the timezone as the very first thing.
Or
Gets request's IPAddr, then geolocation, then tmezone.
The second option is dependent upon 3rd party libraries and 3rd part servers.
Upvotes: 0
Reputation: 10370
For php +5.3 you can use DateTime::createFromFormat. But for previous versions of php, You should use of strtotime()
. here is a example:
$curDate = date('l, F d y h:i:s');
$curDate = strtotime($curDate);
$new = date('Y-m-d H:i:s', $curDate);
Upvotes: 1
Reputation: 499
You could use http://ipinfodb.com/
to detect users localization and as a result users timezone, for instance:
function geoLocalization($ip, $api_key)
{
$params = @file_get_contents("http://api.ipinfodb.com/v2/ip_query.php?key=".$api_key."&ip=".$ip."&timezone=true");
$fields = @new SimpleXMLElement($params);
foreach($fields as $field => $val) {
$result[(string)$field] = (string)$val;
}
return $result;
}
as you get users localization you can use date_default_timezone_set
to set the timezone.
It is good practice to let your users to overwrite this.
You can find all timezones on this site: http://php.net/manual/en/timezones.php
Upvotes: 1