1

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?

patstuart
  • 1,931
  • 1
  • 19
  • 29
Zemogle
  • 584
  • 4
  • 16

3 Answers3

7

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);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
3

Maybe I'm missing something (EDIT: I was, Paul's answer covers it), but you're right. However, this works:

var t = new Date();
t.setUTCFullYear(2014);
t.setUTCMonth(10, 20); // Set day here instead
console.log(t); // Thu Nov 20 2014 12:40:42 GMT-0600 (Central Standard Time)

It also works if you switch the order of the set statements:

var t = new Date();
t.setUTCFullYear(2014);
t.setUTCDate(20);
t.setUTCMonth(10);
Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
0

The problem is a mixture of particular dates and the order of setting individual parts of the date. If you step through what's happening it becomes clearer:

  • New date is initialised as today: Oct 31, 2014
  • Setting the year to 2014: no effect
  • Setting the month to November: Nov 31, 2014 is interpreted as Dec 1, 2014
  • Setting the date to 20: Dec 20, 2014
scronide
  • 12,012
  • 3
  • 28
  • 33