Dave Shuck
Dave Shuck

Reputation: 563

Strange Javascript date discrepency

Can anyone explain the discrepancy in the output below? My code is as follows:

function addDaysToDate( theDate, days ) {
    var thisDate = new Date( theDate.getTime() + days*24*60*60*1000 );
    return new Date( thisDate );
}

var dt = new Date( '5/20/2014' ); 

for (i=0;i<6;i++)   {
    var dt = addDaysToDate( dt, 7 );
    console.log( dt + '---' + dt.getMonth() + '/' + dt.getDate() + '/' + dt.getYear() );
}

The output generated from that is:

 Tue May 27 00:00:00 PDT 2014---4/27/2014 
 Tue Jun 3 00:00:00 PDT 2014---5/3/2014 
 Tue Jun 10 00:00:00 PDT 2014---5/10/2014 
 Tue Jun 17 00:00:00 PDT 2014---5/17/2014 
 Tue Jun 24 00:00:00 PDT 2014---5/24/2014 
 Tue Jul 1 00:00:00 PDT 2014---6/1/2014 

I have looked at this a number of times, and for the life of my I cannot rationalize why dt.getMonth() shows a month prior to the current month. I have confirmed identical behavior on both Chrome and IE.

Upvotes: 0

Views: 33

Answers (1)

Sam Hanley
Sam Hanley

Reputation: 4755

The number returned by getMonth is zero-based, so January is 0, February is 1, and so on until December which is 11. From the MDN Documentation on Date:

month

Integer value representing the month, beginning with 0 for January to 11 for December.

And:

Date.prototype.getMonth()

Returns the month (0-11) in the specified date according to local time.

Upvotes: 3

Related Questions