获取一段日期的工作日天数,周末天数

/**
* get work days
* @param start 2020-09-01
* @param end 2020-09-30
*/
export const getWeekDayCount = (start: string, end: string) => {
  const range = moment(end).diff(moment(start));
  const d = moment.duration(range);
  const days = d.asDays() + 1; // total days
  const weekDuration = Math.ceil(d.asWeeks()); // week number
  const newStart = moment(start)
    .add(weekDuration * 7, 'days')
    .format('YYYY-MM-DD'); // Calculate using the full week
  let weekendDays = 2 * weekDuration;


  if (newStart !== end) {
    // start week day !== end week day
    const startDay = moment(newStart).format('d');
    const endDay = moment(end).format('d');
    if (Number(endDay) > Number(startDay)) {
      weekendDays -= 2;
    }
    if (startDay === '0') {
      if (endDay !== '6') {
        weekendDays++;
      } else {
        weekendDays += 2;
      }
    }
  } else {
    const endWeek = moment(newStart).format('d'); // if start is 6 or 0, should += 1
    if (endWeek === '0' || endWeek === '6') {
      weekendDays++;
    }
  }
  return {
    weekDays: days - weekendDays,
    weekendDays: weekendDays,
  };
};

使用循环的方式

/**
* @param start 2020-09-01
* @param end 2020-09-30
*/
export const getWeekDayCount = (startDate: string, endDate: string) => {
  const totalDays = moment(endDate).diff(moment(startDate), 'days') + 1;
  const dayOfWeek = moment(startDate).isoWeekday();
  let totalWorkdays = 0;
  let weekendDays = 0;
  for (let i = dayOfWeek; i < totalDays + dayOfWeek; i++) {
    if (i % 7 !== 6 && i % 7 !== 0) {
      totalWorkdays++;
    } else {
      weekendDays++;
    }
  }
  return {
    weekDays: totalWorkdays,
    weekendDays: weekendDays,
  };
};
posted @ 2020-09-09 18:19  啤酒煮鸡蛋  阅读(292)  评论(0编辑  收藏  举报