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

基于日期选择器双参数计算日期间隔内各月份及对应天数咨询

双日期区间月份及当月天数计算方案

功能说明

基于两个日期选择器的输入参数,计算两个日期覆盖的所有月份,月份展示为中文名称,同时输出对应月份的总天数。
示例:输入日期2021-01-01和2021-03-01,输出结果为:一月 31、二月 28、三月 31

实现思路

  • 先将两个日期选择器的输出值统一转为标准Date对象,兼容不同入参格式
  • 遍历从起始日期所在月份到结束日期所在月份的所有时间节点
  • 对每个遍历到的月份,匹配对应中文名称,同时通过取下个月第0天的特性计算当月总天数
  • 按时间顺序整理后输出结果

代码实现(前端JavaScript场景)

/**
 * 获取日期区间内所有月份及对应天数
 * @param {string|number|Date} startDate - 起始日期(日期选择器输出值)
 * @param {string|number|Date} endDate - 结束日期(日期选择器输出值)
 * @returns {string} 格式化后的结果字符串
 */
function getMonthListWithDays(startDate, endDate) {
  const result = []
  // 初始化当前遍历节点为起始月份1号,避免日期溢出问题
  let currentMonth = new Date(new Date(startDate).getFullYear(), new Date(startDate).getMonth(), 1)
  const endMonth = new Date(new Date(endDate).getFullYear(), new Date(endDate).getMonth(), 1)
  // 中文月份映射表
  const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']

  while (currentMonth <= endMonth) {
    const year = currentMonth.getFullYear()
    const monthIndex = currentMonth.getMonth()
    // 当月总天数 = 下个月第0天的日期值
    const daysInMonth = new Date(year, monthIndex + 1, 0).getDate()
    result.push(`${monthNames[monthIndex]} ${daysInMonth}`)
    // 跳到下一个月
    currentMonth.setMonth(monthIndex + 1)
  }
  return result.join('、')
}

// 测试用例
console.log(getMonthListWithDays('2021-01-01', '2021-03-01'))
// 输出:一月 31、二月 28、三月 31

扩展说明

  • 自动兼容闰年2月天数计算,无需额外编写闰年判断逻辑
  • 支持跨年日期区间计算,例如输入2021-12-10和2022-02-05,输出为十二月 31、一月 31、二月 28
  • 如需区分跨年重复月份,可修改结果拼接规则,追加年份信息,例如改为${year}年${monthNames[monthIndex]} ${daysInMonth}

内容的提问来源于stack exchange,提问作者saman usmani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:45:10