Managing timezones with PHP and Javascript

In a current project we need to keep a log of all activities and present that log to the users. And once we start needing to tell users about times we raise the whole spectre of timezones.

After some heated design discussions we narrowed our requirements to needing to provide a choice of two possible display formats for users.

  1. show all activities in (my) local time eg if I’m in Melbourne, show all activities in Melbourne time, even if not completed in Melbourne
  2. show all activities in (their) local time – what we called “original” time eg if I’m in Melbourne, show all activities completed in Sydney in their original Sydney time, show all activities completed in Perth in their original Perth time.

For the latter format to make sense we agreed to add a timezone code to indicate where we were at the time. For convenience these were all given as time +/- UTC. Eg 4:23PM (UTC +11).

implementation – capturing activity times

To allow us to manipulate activity times after recording them we need to record two bits of information:

  • time completed
  • timezone completed in

Our decision for those two was to record the time in UTC and then for the timezone simply record the difference from UTC for the timezone where the activity was completed. That way we knew that whatever we did on display we had a consistent and understandable set of times in the database.

For example, I’m in Sydney (current timezone is UTC+11). An activity I complete at 4pm is recorded in the database as:

  • completion time: 5am that morning (4pm converted to UTC)
  • completion timezone: UTC+11

getting the timezone the activity was completed in

Getting the timezone is easy, and requires a few lines of Javascript added to the client where the activity is completed. So we can get the value to the server to manipulate and record in the database we pass it back to the server as a hidden form variable on our login page.

The magic function we need is getTimezoneOffset. This returns the number of minutes ahead/behind of GMT for the current user. For reasons that become clear when we start looking at presenting dates we convert it to seconds. And for reasons that are lost to us we need to negate the value because it returns the offset the wrong way around. Eg if the client is currently one hour ahead of UTC, getTimezoneOffset returns -60.

Putting all that together adds the following to our login page:

<script language="JavaScript"> 
   var d = new Date(); 
   var offset = 0 - (d.getTimezoneOffset() * 60); 
   document.write ("<input type='hidden' name='offset' value = '" + offset + "' />")
</script>

We added that code to the login form. That way we can capture it once and store as a session variable to use when recording all subsequent activities for that user in the same session.

getting the UTC time the activity was completed at

In getting the time an action was completed we can either take the client time or server time. Doesn’t really matter (if both are confidently accurate) since we’ll convert either to UTC.

For simplicity we chose to work from the server time. In PHP we can get the UTC of the current server time in 2 lines:

$timestamp = time();   
$timestampUTC = $timestamp - date("Z", $timestamp);

The “Z” option for Date returns the offset to UTC in seconds based on the server’s current timezone. And since timestamps simply count seconds it’s simple to add/remove our conversion factor.

You’ll have noticed there are a few config requirements if this approach is going to work. We were able to rely on these being true in our case but you’ll need to check for your own implementation:

  • Javascript enabled on the client
  • correct time (and timezone) set on the client
  • correct time (and timezone) set on the server

If you cannot rely on any of these then you’ve a few changes to make!

displaying times

With our activity recorded in the database as UTC it is a simple task to convert to the display times we require. To provide a different display format, we simply need to choose which offset we apply to the UTC time recorded in the database.

local time

This is the easiest to generate. Simply update the recorded UTC time with the current UTC offset of the client that we captured when they logged in. Since we converted that value to seconds when uploading we simply add it to the UTC timestamp from the server:

$timeLocal = $timeUTC + $_SESSION['offsetClient']; 
$timeLocalDisplay = date("D d M Y H:i:s", $timeLocal);

original time

For original time we just need to apply the offset originally recorded in the database, and then tweak the presentation of the timezone to something legible.

$timeOriginal = $timeUTC + $offsetActivity  //both from the DB
$timeOriginalDisplay = date("D d M Y H:i:s", $timeOriginal);
if ($offsetActivity == 0) { 
   $timeOriginalDisplay .= " (UTC)"; 
} else { 
   if ($offsetActivity > 0) {   
      $timeOriginalDisplay .= " (UTC +" . ($offsetActivity/3600) . ")"; 
   } else {   
      $timeOriginalDisplay .= " (UTC -" . ($offsetActivity/3600) . ")"; 
   } 
}

That code gives us a date like “Mon 23 Jun 2006 12:23:45 (UTC +7)”.

A third option (that we did not implement) was to give the timezone as relative to our own. Eg if we’re at “UTC+4″ the previous date would be “Mon 23 Jun 2006 12:23:45 (+3)”. This format would be easy to calculate as we already have our current timezone recorded as a session variable after login. However no-one really wanted it (or could agree how to present it) so the idea was dropped.

conclusion

So far this design has handled all the requirements we’ve thrown at it. Only changes we made after implementation was to move some of the display conversion code into mySQL so our queries return the dates in the formats we require. Otherwise, all works well.

What’s missing?

There is one glaring whole in the design and that is the ugliness called daylight saving. It becomes an issue if displaying local times. Our design converts the original activity time to the local time based on the current difference between local time and UTC. But if we’ve moved in or out of daylight savings (so the relative difference now is different to what it was then) our calculation will be out.

To manage that we need to know whether we, locally, were in/out of daylight savings when the activity was completed, and whether we are in/out of daylight savings now. Achievable but a not insignificant piece of work. The client agreed and thus we decided to ignore this issue reasoning:

  • a max of one hour out is liveable, and
  • the issue is consistent (meaning a series of activities reported in local time will still present in the correct order, even if for a period of time they are all 1 hour too early/late)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>