javascript 加号 获取下一个日期的日期中的天数(不包括周末)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8451190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:29:33  来源:igfitidea点击:

Add no. of days in a date to get next date(excluding weekends)

javascriptjquery

提问by Nishu Tayal

I have an date, i need to add no. of days to get future date but weekends should be excluded. i.e

我有一个约会,我需要添加否。获取未来日期的天数,但周末应排除在外。IE

input date = "9-DEC-2011";
No. of days to add  = '13';

next date should be "28-Dec-2011"

Here weekends(sat/sun) are not counted.

这里周末(周六/周日)不计算在内。

回答by ShankarSangoli

Try this

试试这个

var startDate = "9-DEC-2011";
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "", noOfDaysToAdd = 13, count = 0;
while(count < noOfDaysToAdd){
    endDate = new Date(startDate.setDate(startDate.getDate() + 1));
    if(endDate.getDay() != 0 && endDate.getDay() != 6){
       //Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
       count++;
    }
}
alert(endDate);//You can format this date as per your requirement

Working Demo

工作演示

回答by user3091762

@ShankarSangoli

@ShankarSangoli

Here's a newer version which avoid recreating a Date object on each loop, note that it's wrapped in a function now.

这是一个较新的版本,它避免在每个循环中重新创建 Date 对象,请注意它现在被包装在一个函数中。

function calcWorkingDays(fromDate, days) {
    var count = 0;
    while (count < days) {
        fromDate.setDate(fromDate.getDate() + 1);
        if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
            count++;
    }
    return fromDate;
}
alert(calcWorkingDays(new Date("9/DEC/2011"), 13));

回答by Harish Anchu

Here is an elegant solution without any looping or external library:

这是一个优雅的解决方案,没有任何循环或外部库:

function addBusinessDaysToDate(date, days) {
  var day = date.getDay();

  date = new Date(date.getTime());
  date.setDate(date.getDate() + days + (day === 6 ? 2 : +!day) + (Math.floor((days - 1 + (day % 6 || 1)) / 5) * 2));
  return date;
}

var date = "9-DEC-2011";
var newDate = addBusinessDaysToDate(new Date(date.replace(/-/g, "/")), 13);
alert(newDate.toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/, '--')); // alerts "28-Dec-2011"

回答by Moisés Hiraldo

This question is quite old, but all the previous answers are iterating over the days one by one. That could be inefficient for a large number of days. This works for me, assuming daysis a positive int and the startDateis a working day:

这个问题很老了,但是之前所有的答案都是一天一天的迭代。在很多天里,这可能是低效的。这对我有用,假设days是一个正整数并且startDate是一个工作日:

function addWorkingDates(startDate, days) {
    current_day = startDate.getDay() - 1; // Week day, starting on Monday
    weekend_days = 2*parseInt((current_day + days)/5);
    startDate.setDate(changed_to.getDate() + days + weekend_days);
}

回答by lamer lamer

or you can be like this

或者你可以像这样

function addWeekdays(date, weekdays) {
    var newDate = new Date(date.getTime());
    var i = 0;
    while (i < weekdays) {
        newDate.setDate(newDate.getDate() + 1);
        var day = newDate.getDay();
        if (day > 1 && day < 7) {
            i++;
        }
    }
    return newDate;
}
var currentDate = new Date('10/31/2014');
var targetDate = addWeekdays(currentDate, 45);
alert(targetDate);

回答by Jee Mok

Using moment.js:

使用moment.js

const DATE_FORMAT = 'DD-MMM-YYYY';

// Adding number of days skipping weekends
function addDays(datestring, numberOfDays) {
  const date = moment(datestring, DATE_FORMAT);

  // Weekend occurrence * 2 days
  const weekendCounts = Math.floor(numberOfDays / 5) * 2;

  // If it is Friday, add additional 2 days to skip the weekend
  if (date.day() === 5) {
    return date.add(numberOfDays + weekendCounts + 2, 'days').format(DATE_FORMAT);
  }
  // If it is Saturday, add additional 1 day to skip the weekend
  if (date.day() === 6) {
    return date.add(numberOfDays + weekendCounts + 1, 'days').format(DATE_FORMAT);
  }

  // Otherwise, add the number of days
  return date.add(numberOfDays + weekendCounts, 'days').format(DATE_FORMAT);
}

console.log(addDays('9-Dec-2011', 13)); // 28-Dec-2011
console.log(addDays('10-Dec-2011', 13)); // 28-Dec-2011 (Saturday, so remain on Friday)
console.log(addDays('11-Dec-2011', 13)); // 28-Dec-2011 (Sunday, so remain on Friday)
console.log(addDays('12-Dec-2011', 13)); // 29-Dec-2011
console.log(addDays('13-Dec-2011', 13)); // 30-Dec-2011
console.log(addDays('14-Dec-2011', 13)); // 31-Dec-2011
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

回答by Greg Quinn

If you want to get the next working day, from a specific date, use the following code...

如果要从特定日期获取下一个工作日,请使用以下代码...

function getNextWorkingDay(originalDate) {
    var nextWorkingDayFound = false;
    var nextWorkingDate = new Date();
    var dateCounter = 1;

    while (!nextWorkingDayFound) {
        nextWorkingDate.setDate(originalDate.getDate() + dateCounter);
        dateCounter++;

        if (!isDateOnWeekend(nextWorkingDate)) {
            nextWorkingDayFound = true;
        } 
    }

    return nextWorkingDate;
}

function isDateOnWeekend(date) {
    if (date.getDay() === 6 || date.getDay() === 0)
        return true;
    else
        return false;
}

回答by SaQiB

try this solution

试试这个解决方案

<script language="javascript">

function getDateExcludeWeekends(startDay, startMonth, startYear, daysToAdd) {
var sdate = new Date();
var edate = new Date();
var dayMilliseconds = 1000 * 60 * 60 * 24;
sdate.setFullYear(startYear,startMonth,startDay);
edate.setFullYear(startYear,startMonth,startDay+daysToAdd);
var weekendDays = 0;
while (sdate <= edate) {
    var day = sdate.getDay()
    if (day == 0 || day == 6) {
        weekendDays++;
    }
    sdate = new Date(+sdate + dayMilliseconds);
} 
sdate.setFullYear(startYear,startMonth,startDay + weekendDays+daysToAdd);
return sdate;
}

</script>

回答by Toph

For some reason it was more intuitive to me to try this recursively. This version doesn't account for holidays, but you could change the isValidfunction to check whatever.

出于某种原因,递归地尝试这个对我来说更直观。此版本不考虑假期,但您可以更改isValid功能以检查任何内容。

function addWeekdaysToDate(date, numberToAdd) {
  var isValid = function(d) { return d.getDay() !== 0 && d.getDay() !== 6 }
  if(Math.abs(numberToAdd) > 1) {
    return addWeekdaysToDate(
      addWeekdaysToDate(date, Math.sign(numberToAdd)),
      numberToAdd - Math.sign(numberToAdd)
    )
  } else if(Math.abs(numberToAdd) === 1) {
    var result = new Date(date)
    result.setDate(result.getDate() + Math.sign(numberToAdd))
    if(isValid(result)) {
      return result
    } else {
      return addWeekdaysToDate(result, Math.sign(numberToAdd))
    }
  } else if(numberToAdd === 0) {
    return date
  }
  return false
}

console.log(addWeekdaysToDate(new Date(), 1))
console.log(addWeekdaysToDate(new Date(), 5))
console.log(addWeekdaysToDate(new Date(), -7))

In certain browsersyou may need a polyfill for Math.sign:

某些浏览器中,您可能需要一个 polyfill Math.sign

Math.sign = Math.sign || function(x) {
  x = +x; // convert to a number
  if (x === 0 || isNaN(x)) {
    return Number(x);
  }
  return x > 0 ? 1 : -1;
}

回答by Tejswita

Try this

试试这个

<html>
<head>


<script type="text/javascript">
function calculate(){
var noOfDaysToAdd = 13;
var startDate = "9-DEC-2011";
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = ""; 
count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6)
{
count++;
}
}
document.getElementById("result").innerHTML = endDate;
}
</script>
</head>
<body>
<div>
Date of book delivery: <span id="result"></span><br /><br />
<input type="button" onclick="calculate();" value="Calculate"/>
<br>
<br>
</div>
</body>
</html>