TypeScript调用new Date()函数出现异常错误年份问题求助
问题成因
- 类型错误:
req.headers中获取的year和month都是字符串格式,执行month + 1时会触发字符串拼接逻辑,你传入的month是字符串"6",最终得到的是拼接结果"61",而不是预期的数值7。 - Date参数溢出自动折算规则:JS的
Date构造函数接收的月份参数为011(对应112月),如果传入超出范围的数值,会自动将超出部分折算到年份上。字符串"61"传入后会被隐式转为数字61,2021年叠加61个月等价于5年零1个月,最终得到的就是2026年1月的日期,和你看到的输出结果完全匹配。
解决方案
先将从请求头拿到的year、month转为数值类型后再做日期计算,修正后的代码如下:
// 先转成数值类型 const year = Number(req.headers.year); const month = Number(req.headers.month); const date_range_from = new Date(year, month, 1); const date_range_to = new Date(year, month + 1, 1); console.log("year, month: ", year, month) console.log("date_range_from, date_range_to: ", date_range_from, date_range_to)
可选优化:可以增加合法性校验,避免请求头参数异常导致的计算错误:
const year = Number(req.headers.year); const month = Number(req.headers.month); if (isNaN(year) || isNaN(month) || month < 0 || month > 11) { // 抛出参数错误或者做兜底处理 }
内容的提问来源于stack exchange,提问作者Kid_Learning_C
相关产品推荐
相关产品推荐

