JavaScript如何根据给定年月获取对应月份的第一天和最后一天
问题根因
- JavaScript内置
Date对象的月份参数采用0起始计数规则:0代表1月、11代表12月,你传入的10会被识别为11月,和你预期的10月存在1个月的偏移 - 直接打印
Date对象默认输出UTC标准时间(后缀带Z),和本地时区存在时差,会进一步导致日期显示和预期不符
修复代码
function getMonthFirstAndLastDay(year, month) { // 将传入的1-12自然月转换为Date对象需要的0-11计数 const jsMonth = month - 1; // 当月第一天直接取当月1号 const firstDay = new Date(year, jsMonth, 1); // 当月最后天取下一个月的第0天,会自动回退到当月最后一天 const lastDay = new Date(year, jsMonth + 1, 0); // 格式化日期为YYYY-MM-DD格式,使用本地时间方法避免时区问题 const format = (date) => { const yearPart = date.getFullYear(); const monthPart = String(date.getMonth() + 1).padStart(2, '0'); const dayPart = String(date.getDate()).padStart(2, '0'); return `${yearPart}-${monthPart}-${dayPart}`; } return { firstDay: format(firstDay), lastDay: format(lastDay) } } // 测试用例:传入2021年10月 const result = getMonthFirstAndLastDay(2021, 10); console.log(result.firstDay); // 输出 2021-10-01 console.log(result.lastDay); // 输出 2021-10-31
内容的提问来源于stack exchange,提问作者riyan193
相关产品推荐
相关产品推荐

