【发布时间】:2021-03-31 02:05:40
【问题描述】:
我得到了这段代码(来自 GitHub)它完全符合我的要求,除了生成的月份比 JavaScript 代码中的月份提前一个月。此代码中的月份是 02(二月),但屏幕上生成的月份是 03(三月)。我在这里没有看到什么?日期是这样写的吗?
<script>
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate,1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2021,02,22), new Date(2021,02,27));
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
</script>
【问题讨论】:
-
在
new Date()中,月份数字从 0 到 11,而不是从 1 到 12。 -
嗨 Pointy,为什么它只影响月份?我必须编写一个函数来更改月份吗?
-
这就是 JavaScript 25 年来一直工作的方式。我不能说这是个好主意,但祝你好运:)
-
当我从 Jquery 日期选择器中获取值时,最好的写法是什么?会不会像 document.getElementByName().innerHTML = startDate.getMonth() - 1;
标签: javascript arrays date