views:

98

answers:

2

My locale settings are :

Short Date Format : dd/mm/yyyy , Long Date Format dd MMMM yyyy

so why does

var d = new Date("8/10/2009")
alert(d.toLocaleDateString());

throw up 10 August 2009

or

var d = new Date("15/10/2009");

throw up 10th March 2010

+1  A: 

Try this instead.

var myDate=new Date();
myDate.setFullYear(2010,0,14);
Daniel A. White
In reality I'm doing var myDate= new Date(el.value) so not a great option here.
+3  A: 

Where the system gets the 10 August date from should be obvious, even if you don't get why yet. But it's less easy to understand how it gets "10th March 2010" from "15/10/2009". So in case you missed it:

Assume for a moment the Date object has already decided it's using a "M/d/y" format, so the the first part (15) is the month. How would it handle that? What happens is that it starts with the year and builds the date "1/1/2009". It then advances to the 15th month, to give you March of 2010. Add the 10 days and there you go.

For the "why" of it, notice that you had to call toLocaleDateString() to get it to output in your particular locale format. But your new Date() makes no similar mention of locale anywhere. So it's just using it's invariant built-in culture.

Joel Coehoorn
But if my locale date format is dd/mm/yyyy , new Date("8/10/2009") i thought would output 8th Oct 2009 when .tolocaleDateString() is called (?)
new Date() is a completely separate expression and doesn't care that you used toLocaleDateString() elsewhere.
Joel Coehoorn
so new Date() automatically assumes US date format. bit racist isn't it
What 'race' would that be? We have all kinds here, you know. Though I agree it could be easier to parse a date in a specific format. You may want to take a fixed date (new Date(3,2,1)) and evaluate it's toLocaleDateString() output to get an idea what you're dealing with.
Joel Coehoorn
ok, thanks for your help