momentjs计算一段时间内包含多少周中周末天数

该段代码思路为计算好多少个整周,然后在计算相加非整周数据,具体见代码,希望对大家有用 ^_^

/**
 * 计算一段时间内包含多少天周中  多少天周末
 * @param start
 * @param end
 * @returns {{weekDays: number, weekendDays: number}}
 */
export function getWeekDayCount(start,end) {
  const range = moment(end).diff(moment(start));
  const d = moment.duration(range);
  const days = d.asDays() + 1;  // 总天数  因为需要包含首尾所以加1
  const weekDuration = Math.floor(d.asWeeks()); // 计算周数
  const newStart = moment(start).add(weekDuration*7,'days').format('YYYY-MM-DD');  //整周的拿开 尾数为新的起始点
  let weekendDays = 2*weekDuration;

  if(newStart !== end){ // 不是满周计算后续
    let startDay = moment(newStart).format('d');
    let endDay = moment(end).format('d');
    if(startDay === '6'){ // 结束日期必然小于6
      weekendDays++
      if(endDay >= 0){
        weekendDays++
      }
    }else if(startDay === '0'){
      weekendDays++
      if(endDay === '6'){ // 开始日期等于0 结束为0则为整周   不可能
        weekendDays++
      }
    }
  }else{
    const endWeek = moment(newStart).format('d');  // 因为我这边数据包含首尾  需要扫尾
    if(endWeek === '0' || endWeek === '6'){
      weekendDays++;
    }
  }
  return {
    weekDays: days - weekendDays,
    weekendDays: weekendDays
  }
}
发布了17 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wufantastic/article/details/90766143
今日推荐