2

So I have this JS-code:

var d1 = new Date();
d1.setFullYear(2014);
d1.setMonth(1);
d1.setDate(1);

Should be Feb-01-2014, right? Only it's not... It returns Mar-01-2014 (actually, the full value is "Sat Mar 01 2014 20:54:29 GMT+0100 (Romance Standard Time)"). What the hell? Same thing happens with any other date value.

If I use this code, however, it works fine:

var d1 = new Date(2014, 1, 1, 0, 0, 0, 0);

The result is: Sat Feb 01 2014 00:00:00 GMT+0100 (Romance Standard Time)

Any ideas what's going on?

4 Answers 4

5

Here's what's happening, line for line:

You create a new date object with today's date.

var d1 = new Date(); // d1 = 2014-04-30

Then you set the year to 2014, which it already is, so nothing really happens.

d1.setFullYear(2014); // d1 = 2014-04-30

Here's the tricky part, because now you change the month to February. But this would make the date February the 30th (2014-02-30) which doesn't exist, so the JavaScript will try to find the closest valid date which is first of March (2014-03-01).

d1.setMonth(1); // d1 = 2014-02-30 is not valid so JS makes it 2014-03-01

Then you set the day to the first day of the month, which it already is, so nothing really happens here either.

d1.setDate(1) // d1 = 2014-03-01
1
  • Thanks to everyone who responded! I see now what I did wrong... Problem solved! Commented Apr 30, 2014 at 19:24
2

You need to call setDate first. Basically it's grabbing the month and using the current date and since February doesn't have a 30th, it's defaulting to March.

0

Better to initialize Date, rather than have it default to the current date.

var d1 = new Date(0); // 1 January 1970 00:00:00 UTC
0

Try this:

d1.setFullYear(2014);
d1.setDate(1);
d1.setMonth(1);

What you were doing:

d1.setFullYear(2014);  // change year to 2014 (30 Apr 2014 -> 30 Apr 2014)
d1.setMonth(1);        // change month to 1 (30 Apr 2014 -> 30 Feb 2014, really 2 Mar 2014)
d1.setDate(1);         // change day of month to 1 (2 Mar 2014 -> 1 Mar 2014)

By setting the date first, you're changing the date to 1 Apr 2014 before changing the month.

Not the answer you're looking for? Browse other questions tagged or ask your own question.