1、方法
function getWorkdayCount(start, end) {
let workdayCount = 0;
for (let date = start; date <= end; date.setDate(date.getDate() + 1)) {
if (date.getDay() >= 1 && date.getDay() <= 5) {
workdayCount++;
}
}
return workdayCount;
}
const start = new Date("2023-02-13");
const end = new Date("2023-02-17");
const workdayCount = getWorkdayCount(start, end);
console.log(workdayCount); // 输出为: 3
//在上面的代码中,通过循环,我们逐天检查日期是否在星期一到星期五之间。如果是,则工作日计数器将加1。最终,函数返回工作日计数器。
2、或者
const today = new Date();
//获取当前时间年份
const year = today.getFullYear();
//获取当前时间月份,如果小于10拼接0
const month = today.getMonth() + 1 < 10 ? `0${today.getMonth() + 1}` : today.getMonth() + 1;
//获取当前时间日,小于10拼接0
const day = today.getDate() < 10 ? `0${today.getDate()}` : today.getDate();
//拼接当前时间数据
const formattedToday = `${year}-${month}-${day}`;
//获取数据里的时间。我这里使用的是for循环传入值。这里可以自定义数据 如 2023-02-13
const currentDay = new Date(data.rows[i].REVIEW_CREATE_TIME);
//当前时间
const nowTime = new Date(formattedToday);
//getTime()方法返回毫秒值;如 82374823427(这是瞎输入的,和这个差不多)
const dataTime = currentDay.getTime();
const nowTimeData = nowTime.getTime();
//定义变量用于存储两个时间的时间差(天数)
let workdayCount = 0;
//f+=24 * 3600 * 1000 意味着每次循环,f 的值会增加一个代表一天的毫秒数
for (let f = dataTime; f <= nowTimeData; f += 24 * 3600 * 1000) {
const day = new Date(f);
//当前日期对应的星期几(0代表星期天,1代表星期一,以此类推),所以 day.getDay() >= 1 && day.getDay() <= 5 的含义就是如果当前日期是星期一到星期五中的一天,则执行该判断。
如果判断成立,那么 workdayCount 变量就会被加一。
if (day.getDay() >= 1 && day.getDay() <= 5) {
workdayCount++;
}
}
//这里我是给data里rows数组新增加了一个变量。来存储计算出来的时间差。为了展示使用。可以更换成console.log(workdayCount)打印出来试试看
data.rows[i].stagnation = workdayCount;
3、使用java实现。在 Java 中使用 Calendar 对象计算两个日期之间的工作日
这个代码的实现方法是,每次循环时从开始日期加上 1 天,并使用 get(Calendar.DAY_OF_WEEK) 函数判断这一天是否是周六或周日,如果不是,workdays 计数器就加 1。当 startDate 的日期晚于 endDate 时,循环就结束了,并返回 workdays 的结果。
public static void main(String[] args) {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2022, Calendar.JANUARY, 1);
end.set(2022, Calendar.DECEMBER, 31);
int workdays = getWorkingDaysBetweenTwoDates(start, end);
System.out.println("工作天数: " + workdays);
}
public static int getWorkingDaysBetweenTwoDates(Calendar startDate, Calendar endDate) {
int workdays = 0;
while (!startDate.after(endDate)) {
if (startDate.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startDate.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
workdays++;
}
startDate.add(Calendar.DATE, 1);
}
return workdays;
}