Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adjust time zone

Tags:

date

php

datetime

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.

like image 914
Anonymous Avatar asked Feb 01 '11 06:02

Anonymous


1 Answers

  1. Have the user choose their time zone

  2. 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.

  3. Use date('Z') to get that time zone's offset from GMT in seconds

  4. Convert your stored date to a timestamp with strtotime -- UNIX timestamps are always GMT, so you now have the time in GMT.

  5. Add the offset from step 3 to convert that time to the user's time zone.

  6. 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;
like image 186
Dan Grossman Avatar answered Sep 29 '22 13:09

Dan Grossman