You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:45:03