Skip to content

Instantly share code, notes, and snippets.

@SamChristy
Created September 21, 2013 17:49
Show Gist options
  • Select an option

  • Save SamChristy/6652640 to your computer and use it in GitHub Desktop.

Select an option

Save SamChristy/6652640 to your computer and use it in GitHub Desktop.
Notes on timezones from ages ago - posted for the potential benefit of anyone else.
<?php
// ### How to Handle Timezones Correctly! ###
// Time is a presentation issue. Always store date/time as UTC, then convert it
// to the user's timezone post retrieval and prior to output.
//
// Take a calendar application, for example. If Bob wants to play video games at
// 13:00 on 2011/09/01 and Bob lives in London, which would be in BST (UTC+1),
// then this should be saved in UTC (i.e. less an hour). Then, if Jerry lives in
// New York and wants to play the same game with Bob at the same time, the date
// would be retrieved from the database and converted to Jerry's timezone, which
// would be five hours behind Bob's at that time (UTC-1) and 08:00 for Jerry.
// Step 1. Before storage as Unix Timestamp
$timezone = new DateTimeZone('America/New_York');
// The timezone must either be set at the same time as the date/time, using the
// constructor, like this:
$dt = new DateTime('2011/09/01 08:00', $timezone);
// Or *before* the date/time, using the DateTimeZone methods, like so:
$dt->setTimeZone($timezone);
$dt->setDate(2011, 9, 1);
$dt->setTime(8, 0);
// If the timezone is changed subsequently, it only affects the object's output
// *not* the timestamp (which is automatically coerced to UTC).
$dt->setTimeZone(new DateTimeZone('Europe/London'));
$date = $dt->format('r');
$ts = $dt->getTimeStamp();
// Step 2. After retrieval as Unix Timestamp
// DateTime objects constructed from timestamps (like the one below) are always
// in UTC, the timezone needs to be set to the user's timezone before output.
$dt2 = new DateTime("@$ts");
$dt2->setTimeZone($timezone);
$date2 = $dt2->format('r');
$ts2 = $dt2->getTimeStamp();
echo "1st Timestamp: $ts\n";
echo "1st Date: $date\n";
echo "2nd Timestamp: $ts2\n";
echo "2nd Date: $date2\n";
// *The DateTime timestamp is coerced to UTC by simply taking away the current offset.
//
// Relevant documentation: http://www.php.net/manual/en/book.datetime.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment