Localized Date Parsing in JavaScript

Well heck. The JavaScript Date constructor’s not as smart as I thought (at least in Mozilla and Safari.)

I found this out while round-tripping a date.

I’m adding a row to a table.

var d = new Date ('m/y/d');

var ds = d.toLocaleDateString ();

The localized string became a text node in a table cell.

Later on, I want to use that date, so I get a copy from the table cell and parse it into another Date object.

var nd = new Date (ds);

When you change from an English language locale, that last line fails because JavaScript does not appear to be able to parse a string such as ‘Dienstag, 7. September 2004′ into a Date object.

So, if you want to have JavaScript do something inteligent with date strings embedded in a page, you’ll need to attach a parsable date string to the content. If dates are unique within the page, you could use the id attribute.

<span class="date" id="date-9-7-2004">Dienstag, 7. September 2004</span>

In practice, I do that programatically:

var d = new Date ();

var x = document.createTextNode (d.toLocaleDateString());

var span = document.getElementsByTagName ('span')[0];

span.onclick = dateHandler;

span.id = 'date-' + (d.getMonth () + 1) + '-' +

    d.getDate () + '-' + d.getFullYear ();

span.appendChild (x);

Then attach a handler to all the spans with class = 'date'. Since ids start with alpha characters, you’ll need to store the date as something other than 9/7/2004.

I’ve put this into a toy example.

Link

More like this: , .