Tuesday 12 July 2011

Storing and Displaying dates in different timezones in PHP


Situation
I want a user in, say, California to be able to post a comment that will be stored in MySQL. I then want a user in, say, Texas to be able to view the comment with the post date adjusted to his or her time zone.
Proposed Solution
Storing
  1. Run the following at the start of the application so that all date functions use UTC timezone:date_default_timezone_set('UTC');
  2. $Date = new DateTime(); to get a DateTime object with the current date and time in UTC.
  3. Use $Date->format() to get the value to insert into the datetime type column in MySQL.
Displaying
  1. Get the user's timezone information from JavaScript and store it in a cookie.
  2. Run a MySQL SELECT query to retrieve the datetime column value.
  3. $Date = new DateTime($row['time']); to instantiate a DateTime object with the stored UTC time.
  4. $Date->setTimezone(new DateTimeZone($userTimezone)); to adjust the UTC time to the user's timezone.
  5. Display using $Date->format();

No comments:

Post a Comment