如何使用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)