Skip to content Skip to sidebar Skip to footer

Javascript Date Bug February 2014

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,

Solution 1:

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

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

var d1 = newDate(); // 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

Solution 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.

Solution 3:

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

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

Solution 4:

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.

Post a Comment for "Javascript Date Bug February 2014"