如何使用javascript
添加工作日(即星期一至星期五),在必要時自動添加週末?使用Javascript添加工作日
因此,如果我今天要加5個工作日(2016年11月22日星期二),我想獲得Tue. 29th Nov. 2016
而不是Sun. 27th Nov. 2016
。
如何使用javascript
添加工作日(即星期一至星期五),在必要時自動添加週末?使用Javascript添加工作日
因此,如果我今天要加5個工作日(2016年11月22日星期二),我想獲得Tue. 29th Nov. 2016
而不是Sun. 27th Nov. 2016
。
它可以使用Date
的setDate
功能(結合getDate
)添加到天的日期,即 -
var myDate = new Date(); // Tue 22/11/2016
myDate.setDate(myDate.getDate() + 3); // Fri 25/11/2016
所以,一旦你計算的工作日時間內的週末天數您可以將開始日期和所需數量的工作日添加到開始日期以獲取最終日期。
這個功能應該工作,但顯然這不會考慮國家法定節假日 -
function addWorkDays(startDate, days) {
// Get the day of the week as a number (0 = Sunday, 1 = Monday, .... 6 = Saturday)
var dow = startDate.getDay();
var daysToAdd = parseInt(days);
// If the current day is Sunday add one day
if (dow == 0)
daysToAdd++;
// If the start date plus the additional days falls on or after the closest Saturday calculate weekends
if (dow + daysToAdd >= 6) {
//Subtract days in current working week from work days
var remainingWorkDays = daysToAdd - (5 - dow);
//Add current working week's weekend
daysToAdd += 2;
if (remainingWorkDays > 5) {
//Add two days for each working week by calculating how many weeks are included
daysToAdd += 2 * Math.floor(remainingWorkDays/5);
//Exclude final weekend if remainingWorkDays resolves to an exact number of weeks
if (remainingWorkDays % 5 == 0)
daysToAdd -= 2;
}
}
startDate.setDate(startDate.getDate() + daysToAdd);
return startDate;
}
//And use it like so (months are zero based)
var today = new Date(2016, 10, 22);
today = addWorkDays(today, 5); // Tue Nov 29 2016 00:00:00 GMT+0000 (GMT Standard Time)
它也可以被添加到Date
原型 -
Date.prototype.addWorkDays = function (days) {
var dow = this.getDay();
var daysToAdd = parseInt(days);
// If the current day is Sunday add one day
if (dow == 0) {
daysToAdd++;
}
// If the start date plus the additional days falls on or after the closest Saturday calculate weekends
if (dow + daysToAdd >= 6) {
//Subtract days in current working week from work days
var remainingWorkDays = daysToAdd - (5 - dow);
//Add current working week's weekend
daysToAdd += 2;
if (remainingWorkDays > 5) {
//Add two days for each working week by calculating how many weeks are included
daysToAdd += 2 * Math.floor(remainingWorkDays/5);
//Exclude final weekend if the remainingWorkDays resolves to an exact number of weeks
if (remainingWorkDays % 5 == 0)
daysToAdd -= 2;
}
}
this.setDate(this.getDate() + daysToAdd);
};
//And use it like so (months are zero based)
var today = new Date(2016, 10, 22)
today.addWorkDays(5); // Tue Nov 29 2016 00:00:00 GMT+0000 (GMT Standard Time)
我認爲你可以使用moment-business-days。
實施例:
// 22-11-2016 is Tuesday, DD-MM-YYYY is the format
moment('22-11-2016', 'DD-MM-YYYY').businessAdd(5)._d // Tue Nov 29 2016 00:00:00 GMT-0600 (CST)