Javascript getUTCMonth() returns 0 for December?

前端 未结 3 2086
小鲜肉
小鲜肉 2021-01-05 03:24

MY fiddle here is returning 0 for December

http://jsfiddle.net/3CpXz/

var exploded = \"2011-12-25\".split(\'-\');
var d = new Date(exploded[0], explo         


        
3条回答
  •  一个人的身影
    2021-01-05 03:32

    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

提交回复
热议问题