Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Try this instead.

var myDate=new Date();
myDate.setFullYear(2010,0,14);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top