6

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.

Anonymous
  • 1,823
  • 7
  • 23
  • 29
  • 1
    possible duplicate of [Adjusting time zone in PHP with DateTime / DateTimeZone](http://stackoverflow.com/questions/1445087/adjusting-time-zone-in-php-with-datetime-datetimezone) –  Feb 01 '11 at 06:09

2 Answers2

7
  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;
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