Javascript getUTCMonth () returns 0 for December?

My violin returns here for December 0

http://jsfiddle.net/3CpXz/

var exploded = "2011-12-25".split('-'); var d = new Date(exploded[0], exploded[1], exploded[2]); document.write("year"+d.getUTCFullYear()+ " month"+d.getUTCMonth()+" day"+d.getUTCDate()); 

Why is this?

+7
source share
3 answers

No, it's the other way around: you define the date as if it were in January .

See the documentation on Date() :

month . An integer representing the month, starting at 0 , from January to December 11th.

You provided 12 , so it was considered as 0 (January).

If you need proof , see a modified version of the script displaying the entire date and time .

+9
source

Did you notice that he prints 2012 for the year? The problem is that he uses the month based on 0, so he believes that month 12 of this year is actually the 0th month of the next year. In other words, 0 is January and 11 is December, so January 12 of next year.

You need to subtract 1 from the month for human reading:

 var d = new Date(exploded[0], exploded[1] - 1, exploded[2]); 

If I changed the program to this:

 var exploded = "2011-12-25".split('-'); var d = new Date(exploded[0], exploded[1] - 1, exploded[2]); document.write(d.toString()); 

It prints: Sun Dec 25 00:00:00 EST 2011

+7
source

December is 11 in the Date object. You will need to subtract 1 to make it 0-indexed.

http://www.w3schools.com/jsref/jsref_getutcmonth.asp

+2
source

All Articles