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.
Have the user choose their time zone
Use that zone name or offset with date_default_timezone_set
to 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 seconds
Convert 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 date
again 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With