Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript getUTCMonth() returns 0 for December?

Tags:

javascript

My fiddle here is returning 0 for December

https://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?

like image 227
williamsandonz Avatar asked Dec 01 '11 00:12

williamsandonz


2 Answers

No, this is the other way around: you are defining date as if it was in January.

See the documentation on Date():

month - Integer value representing the month, beginning with 0 for January to 11 for December.

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

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

like image 98
Tadeck Avatar answered Nov 19 '22 06:11

Tadeck


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

You need to subtract 1 from the human-readable month:

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

If I change 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

like image 8
Gabe Avatar answered Nov 19 '22 05:11

Gabe