JavaScript获取指定日期前一天代码运行结果不符合预期,该如何解决
问题原因
- 创建Date实例时已经正确适配了月份0索引规则(传参使用
month - 1),但输出月份时没有将getMonth()返回的0索引值转换为日常使用的1-12计数:getMonth()返回值范围为0(对应1月)到11(对应12月),直接拼接输出会比实际月份小1,就是输出结果不符合预期的核心原因。 - 你提供的第二个测试用例当前代码运行实际输出为
2016-8-30,和预期的2016-9-30差的就是这一步加1的处理。
修正后的代码
function getPreviousDay(year, month, day) { const date = new Date(year, month - 1, day); // 适配JS Date的0索引规则,传入月份减1 date.setDate(date.getDate() - 1); // 输出月份时加1,转换为1-12的常规计数 console.log(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`); } getPreviousDay(2016, 9, 30); // 输出 2016-9-29,符合预期 getPreviousDay(2016, 10, 1); // 输出 2016-9-30,符合预期
补充说明:如果需要统一输出两位的月份、日期格式,可以增加补零处理,示例如下:
function getPreviousDay(year, month, day) { const date = new Date(year, month - 1, day); date.setDate(date.getDate() - 1); const format = num => String(num).padStart(2, '0'); console.log(`${date.getFullYear()}-${format(date.getMonth() + 1)}-${format(date.getDate())}`); }该版本输出为
2016-09-29、2016-09-30这种标准格式。
内容的提问来源于stack exchange,提问作者user965851
相关产品推荐
相关产品推荐

