tags:

views:

52

answers:

2

Hi Folks,

I'm curious what would be the best practice to extend the Date constructor.

The problem I'm facing is, that the Internet Explorer (< 7+8) can't parse a date like

new Date('2010-05-11');

I have to admit that this is not a standard method to parse, anyways FireFox and Chrome perform well on that kind of date string.

Now I'm wondering, should I just split/parse/rebuild the string before calling new Date() or is there a more elegant solution ?

update

I would highly prefer a native js method to accomplish that. If there isn't a way to somehow add a custom parsing I'll just transform the datestring.

+1  A: 

DateJS will parse all sorts of different strings, but you probably don't need it if you're just doing something small time. A split/parse/rebuild IMO is more elegant than attaching another script to your page:

var dStr = '2010-05-11'.split('-');
var d = new Date(dStr[0], dStr[1] - 1, dStr[2]);

Just remember the month parameter for Date() is zero-based, whereas the date parameter isn't. Weird, I know.

Andy E
That is exactly what I'm doing right now. I just hoped that there maybe is a native method to somehow extend the Date object itself (which seems more elegant to me). It's more like an academic question. +1 anyway
jAndy
@jAndy: I'm not aware of any native solution, short of wrapping `Date()` or `Date.parse()`.
Andy E
+1  A: 

I think it almost always pays-off to use a library for date parsing rather than depending on the browser's native parsing functionality.

Leaving all the fluff they bring, the least minimum that your application should have is being able to parse simple dates such as yours (yyyy-mm-dd) in a consistent manner across all browsers.

If the browsers can't guarantee that, then there's no point in manipulating the date string to a format that appeases all browsers. If the source string itself is in a non-standard format, such as 2010-06-08-12:29:53 (note the third dash) that I recently came across on this feed, then it may make sense to standardize that, and after that you come back to the same problem - parsing natively (which IMO is a bad idea) or using a library.

Anurag