Search code examples
javascriptutc

Javascript setUTCMonth does not work for November


I'm getting some really strange behaviour with Javascript date objects.

var t = new Date();
t.setUTCFullYear(2014);
t.setUTCMonth(10);
t.setUTCDate(20);
console.log(t);

This returns: Date {Sat Dec 20 2014 10:26:23 GMT-0800 (PST)}

Whereas if you use t.setMonth(10), you correctly get November. Am I doing something wrong?


Solution

  • This will work as expected tomorrow.

    Today (October 31st), t is initialized with its day as 31. When you set the month to November, you're setting "November 31st", which is corrected to December 1st.

    Then you set the date to 20, but the month has already changed. Set the date first, or better yet, use the two-argument verson of setUTCMonth():

    t.setUTCMonth(10, 20);