How would I take a stored date, like 2011-01-30 18:23:49, and adjust it to any chosen timezone? Is there a simple way such as simply defining the time zone by abbreviation or adding/subtracting x amount of hours? Basically I want users to be able to choose their time zone and this default date be adjusted to fit theirs.
Asked
Active
Viewed 3,918 times
2 Answers
7
Have the user choose their time zone
Use that zone name or offset with
date_default_timezone_setto set the default time zone used in date functions throughout the rest of script execution.Use
date('Z')to get that time zone's offset from GMT in secondsConvert your stored date to a timestamp with
strtotime-- UNIX timestamps are always GMT, so you now have the time in GMT.Add the offset from step 3 to convert that time to the user's time zone.
Use
dateagain to format the timestamp as a string in the desired display format.
Example:
$user_timezone = 'America/Los_Angeles';
$stored_time = '2011-01-30 18:23:49';
date_default_timezone_set($user_timezone);
$timestamp = strtotime($stored_time);
$local_timestamp = $timestamp + date('Z');
$local_date = date('Y-m-d H:i:s', $local_timestamp);
echo $local_date;
Dan Grossman
- 51,866
- 10
- 112
- 101
0
Here comes my solution. I tested it with America/Los_Angeles as the servers timezone, and my timezone as the users. I assume that the time is stored using the servers timezone.
<?php
// My (user) timezone
$user_timezone = 'Europe/Berlin';
// Server timezone
$stored_timezone = 'America/Los_Angeles';
// Date/Time stored in your DB, using timezone of the server (yours, that is)
$stored_datetime = '2011-01-29 22:40:00'; // this is the current time in L.A.
// Setting default to servers timezone if not done before
date_default_timezone_set($stored_timezone);
// converting to unix timestamp
$stored_timestamp = strtotime($stored_datetime);
// setting default to users timezone
date_default_timezone_set($user_timezone);
// converting to timestamp
$user_datetime = date('Y-m-d H:i:s', $stored_timestamp);
// setting default back to servers timezone
date_default_timezone_set($stored_timezone);
echo $user_datetime; // output is my current time
xlttj
- 1,158
- 2
- 10
- 15