JS系列--【获取某一时间的前一个工作日】

方式一:通过计算时间戳

// 1.获取前一天日期(排除周六、周日)
getPrevBusinessDay(date) {
  const dayOfWeek = date.getDay();
  if (dayOfWeek === 1) { // 星期一
    return new Date(date.getTime() - 3 * 24 * 60 * 60 * 1000);
  } else if (dayOfWeek === 0) { // 星期日
    return new Date(date.getTime() - 2 * 24 * 60 * 60 * 1000);
  } else {
    return new Date(date.getTime() - 24 * 60 * 60 * 1000);
  }
}

// 2.使用
let date = new Date('2023-06-05');
let prevBusinessDay = getPrevBusinessDay(date); // 计算出来的是标准时间
let newTime = moment(prevBusinessDay).format('YYYY-MM-DD'); // moment日期格式化
console.log(newTime);// 2023-06-02

方式二:使用moment.js来获取前一个工作日时间

getPreviousWorkdayTime(date) {
  let currentDate = moment(date); // 当前时间
  // 循环向前遍历日期,直到找到工作日为止
  while (currentDate.day() === 0 || currentDate.day() === 6) {
    currentDate = currentDate.subtract(1, 'days');
  }
  return currentDate.valueOf();
}

// 使用示例
const previousWorkdayTime = getPreviousWorkdayTime('2023-06-05');
console.log(moment(previousWorkdayTime).format('YYYY-MM-DD'));

 

posted on 2023-06-01 22:00  码农小小海  阅读(191)  评论(0编辑  收藏  举报

导航