我的约会日期格式为2011-04-01
。当我运行以下代码时,会产生以下结果。
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);
}
结果:
[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)}
我分割的日期和我给出Date对象的数字是4月份,为什么它会在5月生成日期?我对JS有点新鲜,所以可能会有一些我不知道的东西。任何有关改进的帮助或建议都将受到赞赏。
答案 0 :(得分:2)
某些JavaScript日期部分数组基于零:例如天数:0 =&gt;星期日,月份:0 =&gt;一月
参考:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
修改后的代码:http://jsfiddle.net/j4kBE/