跳到主要内容

表单中计算工作日天数

1. 使用场景

在某些场合下,我们需要计算两个特定日期范围内的法定工作日天数。

2. 实现功能

2.1. 配置表单页面

2.2. 计算两个日期之间有多少工作日

将下列代码拷贝至 JS 面板中。

/**
* 计算两个日期之间有多少工作日
* @param {string} startTime 开始日期
* @param {string} endTime 结束日期
* @param {array} chinsesHolidays 中国特殊节假日(调休、补班)
*/
export function getWorkdaysCount(startTime = '', endTime = '', chinsesHolidays = []) {
let currentDate = new Date(startTime);
const endDate = new Date(endTime);
if (currentDate > endDate) {
return 0;
}
let workdaysCount = 0;
while (currentDate <= endDate) {
let dayOfWeek = currentDate.getDay();
let currentDateString = this.utils.formatter('date', currentDate.getTime(), 'YYYY-MM-DD');
if (dayOfWeek > 0 && dayOfWeek < 6) {
// 星期一 - 星期五
if (!chinsesHolidays.includes(currentDateString)) {
workdaysCount++;
}
} else {
// 星期六 - 星期日
if (chinsesHolidays.includes(currentDateString)) {
workdaysCount++;
}
}
currentDate.setDate(currentDate.getDate() + 1);
}
return workdaysCount;
}

贴入之后效果如下:

2.3. 日期组件使用

将下述代码拷贝至页面 JS 中并绑定在日期组件(两个均要绑定,注意修改组件唯一标识)上。

export function onChange({ value }) {
const startDate = this.utils.formatter('date', this.$('< 开始日期 >').getValue(), 'YYYY-MM-DD');
const endDate = this.utils.formatter('date', this.$('< 结束日期 >').getValue(), 'YYYY-MM-DD');
const specialHolidays = [
'2024-01-01',
'2024-02-04',
'2024-02-12',
'2024-02-13',
'2024-02-14',
'2024-02-15',
'2024-02-16',
'2024-02-18',
'2024-04-04',
'2024-04-05',
'2024-04-07',
'2024-04-28',
'2024-05-01',
'2024-05-02',
'2024-05-03',
'2024-05-11',
'2024-06-10',
'2024-09-14',
'2024-09-17',
'2024-09-29',
'2024-10-01',
'2024-10-02',
'2024-10-03',
'2024-10-04',
'2024-10-07',
'2024-10-12',
]; // 2024法定节假日日期
const workdays = this.getWorkdaysCount(startDate, endDate, specialHolidays);
this.$('< 工作日天数 >').setValue(workdays);
}

注意:
1、specialHolidays 参数包含每年的节假日日期,但不包括正常的周末日期,例如:2024.05.04 为周末时间也是特殊法定节假日,只需要填入今年周一至周五休息的日期或周六周日上班的日期。
2、因每年法定节假日日期不同,需手动维护每年法定节假日日期。

3. 实现效果

4. 在线试玩

Copyright © 2024钉钉(中国)信息技术有限公司和/或其关联公司浙ICP备18037475号-4