JavaScript's getDate returns wrong date

The following script returns 20 instead of 21!

var d = new Date("2010/03/21");
document.write(d.getDate());

What am I doing wrong? Is this a JavaScript bug?


Solution 1:

The Date.parse method is implementation dependent (new Date(string) is equivalent to Date.parse(string)).

While this format will be available on modern browsers, you cannot be 100% sure that the browser will interpret exactly your desired format.

I would recommend you to manipulate your string, and use the Date constructor with the year, month and day arguments:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

Solution 2:

It's a daylight saving time issue, because Date() uses local time.

I live in Brazil and Oct-21-2012 is the start of daylight saving time in most of my country, so local dates at Oct-21-2012 between 0:0 and 1:0 doesn't exist in Brazil!

Some people comment here that it works. It happens because the right or wrong hour return depends on the local user country.

See: http://www.timeanddate.com/news/time/brazil-dst-2012.html

In Brazil, in 2012 Java thinks that DST starts at Oct-14 (actually it start at 1 week later)

var dt = new Date(2012,9,14); 
alert(dt.getHours());

produces 1 and

See: http://www.timeanddate.com/time/dst/2013.html

The solution is use UTC (Coordinated Universal Time) time, because there is no Daylight Saving changes and you use a kind of abstract time. In most practical applications there is no problem.

var dt = new Date( Date.UTC(2012, 9, 21, 8, 5, 12));
alert( (dt.getUTCMonth()+1) + '/' + dt.getUTCDate() + '/' + 
        dt.getUTCFullYear() + " " + dt.getUTCHours()+ ':' + 
        dt.getUTCMinutes() + ':' + dt.getUTCSeconds() );

it's easier if someone doesn't use hours, minutes and seconds, just place a dummy hour value greater or equal than 1, as I have shown above.

Solution 3:

Any chance it's treating the string argument as UTC and the resulting Date object as local time, or vice versa? That could throw it off. Compare d.getDate() to d.getUTCDate().