js只比较日期(月日)的大小,不比较年份

需求背景:

     要求验证选择的时间是否在可选的时间范围内(即应用的时间范围),但是可选的时间范围是只有月份和天数,不限制年份,所以选择的时间也只验证月日,不校验年份

解决方案:

 需要比较只有月份和日份的日期的大小。当前想到的只有将月份和日份分别拆分出来做比较,目前考虑可能有五种情形:

   当开始时间的月份和结束时间的月份相同(例如 1.5~1.25):
   1.选择的月份等于可选时间的月份时,那么必须选择的日份大于等于开始的日份,小于等于结束的日份,否则其他都是false
   2.选择的月份不等于应用的月份的都是false

   开始时间的月份小于结束时间的月份(只会小于,没有大于的场景)(例如 1.5~3.25):
   1.选择的月份等于应用的开始月份,那么必须选择的日份大于等于开始的日份(例如 1.10)
   2.选择的月份等于结束的月份,那么选择的日份必须小于等于结束的日份(例如 3.17)
   3.选择的月份大于开始的月份,小于结束的月份(例如 2.10)

上代码案例:

// 可选的时间范围
const minDate = "01-09";
const maxDate = "06-09";

// 当前选择的时间数据
const selectDate = [
"2023-02-11",
"2024-01-11",
"2022-05-11",
"2024-09-11"
];

if (isInRange(minDate, maxDate, selectDate)) {
    console.log('所选数据都在可选范围内');
    } else {
    console.log('存在数据不在可选范围内');
}


// 判断是否在可选时间范围内的方法封装
function isInRange(minDate, maxDate, selectDate) {
const beginTimeArr = minDate.split("-");
const endTimeArr = maxDate.split("-");
if (selectDate && selectDate.length > 0) {
    // 将选择的日期拆分成数组数据,方便拿取月份和时间
    const dateArr = selectDate.map((item) => item.split("-"));
    return dateArr.every((item) =>
    // 判断每一个选择的日期是否在最大最小的日期范围内
    compareMonthAndDay(item, beginTimeArr, endTimeArr)
    );
 } else return false;
}


// 判断每一个选择的日期是否在最大最小的日期范围内的方法封装
function compareMonthAndDay(item, beginTimeArr, endTimeArr) {
// 数组解构赋值,只拿取选择的时间月份和日份
const [, selectMonth, selectDay] = item
const [beginMonth, beginDay] = beginTimeArr
const [endMonth, endDay] = endTimeArr
// 应用日期范围在同一个月
if (beginMonth === endMonth) {
// 只有选择的月份等于应用的开始月份,选择的日大于等于开始日, 小于等于结束日为true,其他情况都是false
   return (
   selectMonth === beginMonth &&
   selectDay >= beginDay &&
   selectDay <= endDay
   );
} else {
  // 应用日期时间范围跨月
  // 选择的月等于开始月,那么选择的日大于等于开始日为true,其他为false
  if (selectMonth === beginMonth) return selectDay >= beginDay;
  // 选择的月等于结束月,那么选择的日小于等于结束日为true,其他为false
      if (selectMonth === endMonth) return selectDay <= endDay;
      // 其他情况: 当选择月大于开始月,小于结束月就为true
      return selectMonth > beginMonth && selectMonth < endMonth;
  }
}

 有更好的方案欢迎告知!(^-^)

posted @ 2023-01-10 16:29  applesky  阅读(593)  评论(0)    收藏  举报