0

My date is in the format of 2011-04-01. When I run the below code the following results.

var dateParts = '2011-04-01'.split('-'); dateParts[0] = parseInt(dateParts[0]); dateParts[1] = parseInt(dateParts[1]); dateParts[2] = parseInt(dateParts[2]); console.log(dateParts); for (i = 0; i <= 13; i++) { var thisDate = new Date(dateParts[0], dateParts[1], dateParts[2] + i); console.log(thisDate); } 

Result:

[2011, 4, 1] Date {Sun May 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Mon May 02 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Tue May 03 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Wed May 04 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Thu May 05 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Fri May 06 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Sat May 07 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Sun May 08 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Mon May 09 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Tue May 10 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Wed May 11 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Thu May 12 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Fri May 13 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} Date {Sat May 14 2011 00:00:00 GMT-0400 (Eastern Daylight Time)} 

The date I split and the number I am giving the Date object are in April, why is it generating a date in May? I'm a bit new to JS so there may be something obvious I am missing. Any assistance or suggestions for improvements would be appreciated.

1 Answer 1

2

Some JavaScript Date part arrays are zero based: e.g. Days: 0 => Sunday, Months: 0 => January

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Modified Code: http://jsfiddle.net/j4kBE/

Sign up to request clarification or add additional context in comments.

5 Comments

Is only the month zero based? Both the day and the year are working correctly.
it's true, but please don't link to w3schools, as it's a terrible resource. see w3fools.com
@wildcard - fair enough, new link ;)
@Icode4food, if you look at the developer.mozilla.org link, you should see that year and day return the actual year/day but month is 0 based (I guess because English and other European languages don't use numbers for months).
I find that sort of inconsistent but if it works I can't complain! Welcome to JS I suppose... :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.