You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

JavaScript中基于自定义业务规则计算两个日期月份差值的实现方案问询

自定义月份差计算方案

根据你的需求,核心规则其实是统计两个日期所覆盖的自然月数量——哪怕只在某个月里占1天,也算一个完整的月份。下面分别用Moment.js和原生JavaScript两种方式实现:

用Moment.js实现

我们可以通过提取两个日期的年份和月份,计算它们之间的月份跨度后再加1(因为同一个月也要算1个月):

function calculateCustomMonthDiff(date1Str, date2Str) {
  let start = moment(date1Str);
  let end = moment(date2Str);
  
  // 确保起始日期早于结束日期,避免负数结果
  if (start.isAfter(end)) {
    [start, end] = [end, start];
  }
  
  // 计算年份差带来的月份数 + 月份本身的差值
  const monthDiff = (end.year() - start.year()) * 12 + (end.month() - start.month());
  // 加1是因为同一个月也要算1个单位
  return monthDiff + 1;
}

// 测试你的业务场景
console.log(calculateCustomMonthDiff('2021-06-1', '2021-06-15')); // 输出 1
console.log(calculateCustomMonthDiff('2021-06-1', '2021-07-15')); // 输出 2
// 额外测试跨年度场景
console.log(calculateCustomMonthDiff('2021-12-1', '2022-2-10')); // 输出 3(覆盖2021.12、2022.1、2022.2)

用原生JavaScript实现(无需依赖库)

如果不想引入第三方库,原生Date对象也能实现同样逻辑,注意原生Date的月份是0-based(0代表1月):

function calculateCustomMonthDiff(date1Str, date2Str) {
  const start = new Date(date1Str);
  const end = new Date(date2Str);
  
  // 确保起始日期早于结束日期
  if (start > end) {
    [start, end] = [end, start];
  }
  
  const startYear = start.getFullYear();
  const startMonth = start.getMonth();
  const endYear = end.getFullYear();
  const endMonth = end.getMonth();
  
  const monthDiff = (endYear - startYear) * 12 + (endMonth - startMonth);
  return monthDiff + 1;
}

// 测试验证
console.log(calculateCustomMonthDiff('2021-06-1', '2021-06-15')); // 1
console.log(calculateCustomMonthDiff('2021-06-1', '2021-07-15')); // 2

规则匹配说明

这个逻辑完全贴合你的需求:

  • 同一自然月内(无论间隔天数):返回1
  • 跨1个自然月(比如6月到7月):返回2
  • 跨N个自然月间隔:返回N+1(比如12月到次年2月,跨2个间隔,返回3)

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

火山引擎 最新活动