Webpage Time Zone Hopping

Nov 4, 2012 / By Yanick Champoux

Tags: ,

Time zones can be darn confusing. Even daylight saving time is enough to throw me into bi-annual bouts of confusion. So when I deal with information on a web site posted by someone in a different time zone, talking about events happening in yet another time zone, it usually doesn’t take very long before my head begins to swim. Of course, the typical way to get around those timezone-ish shenanigans is to display all times relative to UTC, which usually means that a fourth time zone is thrown in the mix. Madness!

So I thought: Wouldn’t it be nice to be able to switch the times back and forth on a webpage. This way, you wouldn’t have to juggle the time differences in your head — you can just see the full thing first from your timezone perspective, then from the other guy’s.

On Your Mark(up)

First, we want to mark the times and dates on the page so that we can manipulate them.

<p>We shall meet at <span class="datetime" timezone="Etc/UTC">2012/10/20 12:34</span>
at the docks.</p>
<p>We strike at <span class="datetime">2012/10/20 14:56</span>.</p>

And because the information is already there, let’s add a css rule to display it:

<style>
    span.datetime:after {
        content: " (" attr(timezone) ")";
    }
</style>

Get(), Set()

Now comes the hard part. We want to move times from one time zone to another. And, it’d be cool to automatically recognize the current user’s time zone to provide a sensible default for our display. Trying to rewrite that from scratch would be silly; instead, let’s use timezone-js for the time zone manipulations and jstimezonedetect for the detection. For the following code to work, I had to slightly tweak timezone-js.

With these two libraries as our base, all we need to do is provide the glue:

function changeTimes() {
    var new_tz = $('select#timezone').val();

    $('.datetime').each(function(){
        var t = $(this);
        var tz = t.attr('timezone') || 'Etc/UTC';
        var dt = new timezoneJS.Date(t.text(), tz);
        dt.setTimezone(new_tz);
        t.attr('timezone',new_tz);
        t.text(dt.toString());
    });
}

$(function(){
    timezoneJS.timezone.zoneFileBasePath = '/time/tz';
    timezoneJS.timezone.init();

    $('select#timezone').val(jstz.determine().name()).change( changeTimes );

    changeTimes();
});

and provide the choice to the user.

<form>
    <select id="timezone" >
        <option selected="selected">Etc/UTC</option>
        <option>America/Montreal</option>
        <option>America/New_York</option>
        <option>Asia/Tokyo</option>
    </select>
</form>

Go!

Et voilà! A bare-bone example can be played with here. It’s not the prettiest thing yet, but it’s perfectly functional.

Leave a Reply

  • (will not be published)

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