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

Node.js中使用Moment.js实现月份维度的日期范围校验

解决方案

核心思路

要实现月份范围校验,关键是先把传入的月份范围转换成区间的起止日期边界,再用Moment.js的日期比较方法判断目标日期是否落在这个区间内:

  • 起始边界:年份+起始月的第一天(如2022年4月 → 01-04-2022)
  • 结束边界:年份+结束月的最后一天(如2022年6月 → 30-06-2022)

完整实现代码

const moment = require('moment');

function validateDateInMonthRange(targetDateStr, startMonth, endMonth, year) {
    // 1. 校验目标日期格式有效性
    const targetDate = moment(targetDateStr, 'DD-MM-YYYY', true);
    if (!targetDate.isValid()) {
        throw new Error('目标日期格式无效,请传入DD-MM-YYYY格式的日期');
    }

    // 2. 生成月份范围的起止边界日期
    const startDate = moment(`${year}-${startMonth}-01`, 'YYYY-MM-DD');
    const endDate = moment(`${year}-${endMonth}-01`, 'YYYY-MM-DD').endOf('month');

    // 3. 判断目标日期是否在区间内(包含起止边界)
    if (!targetDate.isBetween(startDate, endDate, 'day', '[]')) {
        throw new Error(`日期${targetDateStr}不在指定的${startMonth}-${endMonth}-${year}月份范围内`);
    }

    // 校验通过返回true或目标日期对象
    return true;
}

// 测试示例
try {
    // 校验成功的情况
    validateDateInMonthRange('12-05-2022', '04', '06', '2022');
    console.log('日期校验通过');

    // 校验失败的情况
    validateDateInMonthRange('12-07-2022', '04', '06', '2022');
} catch (err) {
    console.error(err.message);
}

代码说明

  • 格式校验:使用moment(targetDateStr, 'DD-MM-YYYY', true)的第三个参数true开启严格模式,确保只有完全匹配DD-MM-YYYY格式的日期才会被判定为有效。
  • 边界生成:
    • 起始边界直接取当月第一天,用YYYY-MM-DD格式初始化Moment对象避免歧义
    • 结束边界先取当月第一天,再调用endOf('month')获取该月最后一天(自动处理2月、31天月份等特殊情况)
  • 区间判断:isBetween方法的第四个参数'[]'表示包含起止边界,若需要排除边界可改为'()'。

注意事项

  • 确保已安装Moment.js:执行npm install moment完成依赖安装
  • 传入的月份参数需为两位字符串(如'04'而非4),避免月份格式不匹配导致的错误

内容的提问来源于stack exchange,提问作者Danjay Rathor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:45:31