Browser-local Time Display

Displaying the time in a web page ofter runs into the problem of which timezone to display. The server's timezone is the easiest yet likely to be incorrect. A logged-in user might have a timezone specified already. The best case for most circumstances is to use the browser's timezone. Its the best way to get a local time for the user looking at the page. Since only the browser knows its local timezone, some client-side javascript is necessary. The server generated html provides a UTC time and the browser converts it to localtime for display.

The system I use is below. Use your server side templating language to fill in the datetime field with an iso8601 date string.


<span>Strategy #64</span>
<time data-format="yyyy-MMM-dd HH:mm" 
        datetime="2012-12-06T18:57:02Z" />

Loop through the time tags in jQuery. I use the xdate javascript time library because of its flexibility.


$('time').each(function(){
  var datetime = new XDate($(this).attr('datetime'))
  var formatted = datetime.toString($(this).attr('data-format'))+" "
  $(this).html(formatted)
})

Which generates the string "Strategy #64 2012-Dec-06 10:57" in html for my west-coast located web browser. Every time tag gets the same treatment. Done!

tags: