判断两个日期是否相差指定年数或月数以内

判断两个日期是否相差指定年数以内

/**
 * 判断两个日期是否相差指定年数以内
 * @param startDate - 开始日期,可以是字符串或 Date 对象
 * @param endDate - 结束日期,可以是字符串或 Date 对象
 * @param years - 指定的年数(默认为 1 年)
 * @returns {boolean} - 如果相差指定年数以内返回 true,否则返回 false
 */
export const isWithinYearsSpan = (
  startDate: string | Date,
  endDate: string | Date,
  years: number = 1
): boolean => {
  const start = new Date(startDate);
  const end = new Date(endDate);

  // 获取年份差
  const yearDiff = end.getFullYear() - start.getFullYear();

  // 如果年份差大于指定年数,直接返回 false
  if (yearDiff > years) return false;

  // 如果年份差小于指定年数,直接返回 true
  if (yearDiff < years) return true;

  // 如果年份差等于指定年数,检查月份和日期
  return (
    end.getMonth() < start.getMonth() ||
    (end.getMonth() === start.getMonth() && end.getDate() <= start.getDate())
  );
};

判断两个日期是否相差指定月数以内

/**
 * 判断两个日期是否相差指定月数以内
 * @param startDate - 开始日期,可以是字符串或 Date 对象
 * @param endDate - 结束日期,可以是字符串或 Date 对象
 * @param months - 指定的月数(默认为 1 个月)
 * @returns {boolean} - 如果相差指定月数以内返回 true,否则返回 false
 */
export const isWithinMonthsSpan = (
  startDate: string | Date,
  endDate: string | Date,
  months: number = 1
): boolean => {
  const start = new Date(startDate);
  const end = new Date(endDate);

  // 获取年份和月份差
  const yearDiff = end.getFullYear() - start.getFullYear();
  const monthDiff = end.getMonth() - start.getMonth();

  // 计算总的月份差
  const totalMonthDiff = yearDiff * 12 + monthDiff;

  // 判断是否在指定月数以内
  if (totalMonthDiff > months) return false;
  if (totalMonthDiff < months) return true;

  // 如果刚好是指定月数,比较日期
  return start.getDate() >= end.getDate();
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值