Simple localized dates with Javascript and Node.js

Wed Nov 12 2014 22:50:00 GMT+0000 (Coordinated Universal Time)

One big benefit with Node.js is that it shares the same architecture as the client side, which simplifies lots of things. When you display a date or a time on a webpage, you may often want to have it be displayed in the visitors local timezone. I’ve seen many complicated examples, but since the string representation of the Javascript Date is complete with timezone information, the time will automatically be localized when you pass that string to a new Date object.

The script that I use to localize dates on this blog and on several other websites looks something like this:

// Converts a date string to the local timezone
var nodeList = document.querySelectorAll('.localdate');
for (var i = 0; i < nodeList.length; i++) {
    nodeList[i].innerHTML = new Date(nodeList[i].innerHTML).toString();
}

or, if you use JQuery, it can be turned into a neat one-liner:

// Converts a date string to the local timezone
$('.localdate').each(function() { $(this).html(new Date($(this).html()).toString()) });

Just slap that to the bottom of your page and it will take the standard string representation from a Date.toString() (originating from the server) contained in a HTML element with the class name of localdate and repackage it in a new Date object, which will automatically convert the date into the local timezone on the client!

Example

HTML

<span class="localdate">Fri Jun 29 2012 18:55:59 GMT+0200 (W. Europe Daylight Time)</span>

Result

Fri Jun 29 2012 18:55:59 GMT+0200 (W. Europe Daylight Time)

Unless you’re in the same timezone as me (GMT+2), you should see a different time than 18:55 above. If you also want the date to look nice, you can use an extension library like Datejs or Moment.js to format it to your hearts content!

Who?
What?
My personal portfolio of things I come up with when I'm bored.