问题描述
给定一个日期,获取未来三个月内的日期,唯独给定11月份的日期时有错误
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
function count() {
const now = new Date('2018/11/10 13:42:33');
const date = new Date('2018/11/10 13:42:33');
// const now = new Date('2018/12/10 13:42:33');
// const date = new Date('2018/12/10 13:42:33');
const currentYear = now.getFullYear();
const currentMonth = now.getMonth();
const currentDay = now.getDate();
date.setMonth(currentMonth + 3); // 设定三个月后的月份
const dayCount = Math.floor((date.getTime() - now.getTime()) / 86400000); // 三个月后与给定日期的相差天数
for (let i = 0; i < dayCount; i++) {
now.setFullYear(currentYear);
now.setMonth(currentMonth);
now.setDate(currentDay + i);
console.log(now.toLocaleDateString());
}
}
count();
now
和date
设定为其他月份时正常,唯独设置为11月份会出现缺少1月1日和1月2日的情况,如下图:
但是当我把循环增值改为2时,就正常了:
function count() {
const now = new Date('2018/11/10 13:42:33');
const date = new Date('2018/11/10 13:42:33');
// const now = new Date('2018/12/10 13:42:33');
// const date = new Date('2018/12/10 13:42:33');
const currentYear = now.getFullYear();
const currentMonth = now.getMonth();
const currentDay = now.getDate();
date.setMonth(currentMonth + 3); // 设定三个月后的月份
const dayCount = Math.floor((date.getTime() - now.getTime()) / 86400000); // 三个月后与给定日期的相差天数
for (let i = 0; i < dayCount; i+=2) {
now.setFullYear(currentYear);
now.setMonth(currentMonth);
now.setDate(currentDay + i);
console.log(now.toLocaleDateString());
}
}
count();
稳健的做法:
题主的为啥有问题? 因为答主一直在复用一个 now 对象. 我来解释一下出错的场景. 当 now 为 2018/12/31 时. 进入下一个循环.
Duang! 就是此刻, now 的 date 此时是 2018/11/31, 但是 11月是没有31日的, 所以 now 此时自动矫正变成 2018/12/1. 本来是从 2018/11 开始加上 day 偏移得到新的日期, 现在突然变成从 12月开始算了, 多了一个月! 这就是从 2018/12/31 突然变成 2019/1/31 的原因.
基于题主的代码我们只需要在每次循环时先把日期设为1号就好了: