在javascript日期计算中排除周末

时间:2022-11-30 09:00:03

I have two sets of codes that work. Needed help combining them into one.

我有两组代码可以工作。需要帮助将它们合二为一。

This code gets me the difference between two dates. works perfectly:

这段代码让我了解了两个日期之间的区别。完美的工作:

function test(){var date1 = new Date(txtbox_1.value);    var date2 = new Date(txtbox_2.value);var diff = (date2 - date1)/1000;var diff = Math.abs(Math.floor(diff));var days = Math.floor(diff/(24*60*60));var leftSec = diff - days * 24*60*60;var hrs = Math.floor(leftSec/(60*60));var leftSec = leftSec - hrs * 60*60;var min = Math.floor(leftSec/(60));var leftSec = leftSec - min * 60;txtbox_3.value = days + "." + hrs; }

source for the above code

上述代码的来源

The code below by @cyberfly appears to have the answer of excluding sat and sun which is what i needed. source. However, its in jquery and the above code is in JS. Therefore, needed help combining as i lacked that knowledge :(

@cyberfly下面的代码似乎有了排除sat和sun这个我需要的答案。资源。但是,它在jquery和上面的代码是在JS中。因此,需要帮助结合,因为我缺乏知识:(

<script type="text/javascript">$("#startdate, #enddate").change(function() {       var d1 = $("#startdate").val();var d2 = $("#enddate").val();        var minutes = 1000*60;        var hours = minutes*60;        var day = hours*24;        var startdate1 = getDateFromFormat(d1, "d-m-y");        var enddate1 = getDateFromFormat(d2, "d-m-y");        var days = calcBusinessDays(new Date(startdate1),new Date(enddate1));             if(days>0){ $("#noofdays").val(days);}else{ $("#noofdays").val(0);}});</script>

EDITMade an attempt at combining the codes. here is my sample. getting object expected error.

EDITMade尝试组合代码。这是我的样本。获得对象预期错误。

function test(){var date1 = new Date(startdate.value);    var date2 = new Date(enddate.value);var diff = (date2 - date1)/1000;var diff = Math.abs(Math.floor(diff)); var days = Math.floor(diff/(24*60*60));var leftSec = diff - days * 24*60*60;var hrs = Math.floor(leftSec/(60*60));var leftSec = leftSec - hrs * 60*60;var min = Math.floor(leftSec/(60));var leftSec = leftSec - min * 60;var startdate1 = getDateFromFormat(startdate, "dd/mm/yyyy hh:mm");var enddate1 = getDateFromFormat(enddate, "dd/mm/yyyy hh:mm");days = calcBusinessDays(new Date(startdate1),new Date(enddate1));           noofdays.value = days + "." + hrs; }start: <input type="text" id="startdate" name="startdate" value="02/03/2015 00:00">end: <input type="text" id="enddate" name="enddate" value="02/03/2015 00:01"><input type="text" id="noofdays" name="noofdays" value="">

4 个解决方案

#1


9  

When determining the number of days between two dates, there are lots of decisions to be made about what is a day. For example, the period 1 Feb to 2 Feb is generally one day, so 1 Feb to 1 Feb is zero days.

在确定两个日期之间的天数时,需要做出很多关于一天的决定。例如,2月1日至2月2日期间通常为一天,因此2月1日至2月1日为零天。

When adding the complexity of counting only business days, things get a lot tougher. E.g. Monday 2 Feb 2015 to Friday 6 February is 4 elapsed days (Monday to Tuesday is 1, Monday to Wednesday is 2, etc.), however the expression "Monday to Friday" is generally viewed as 5 business days and the duration Mon 2 Feb to Sat 7 Feb should also be 4 business days, but Sunday to Saturday should be 5.

当增加仅计算工作日计算的复杂性时,事情变得更加艰难。例如。 2015年2月2日星期一至2月6日星期五是4天过去了(星期一到星期二是1,星期一到星期三是2等),但是“星期一到星期五”这个词通常被视为5个工作日,持续时间为2月2日星期一2月7日星期六也应该是4个工作日,但星期日到星期六应该是5个工作日。

So here's my algorithm:

所以这是我的算法:

  1. Get the total number of whole days between the two dates
  2. 获取两个日期之间的总天数

  3. Divide by 7 to get the number of whole weeks
  4. 除以7得到整周的数量

  5. Multiply the number of weeks by two to get the number of weekend days
  6. 将周数乘以2得到周末天数

  7. Subtract the number of weekend days from the whole to get business days
  8. 从整体中减去周末天数以获得工作日

  9. If the number of total days is not an even number of weeks, add the numbe of weeks * 7 to the start date to get a temp date
  10. 如果总天数不是偶数周数,请将周数* 7添加到开始日期以获取临时日期

  11. While the temp date is less than the end date:
    • if the temp date is not a Saturday or Sunday, add one the business days
    • 如果临时日期不是星期六或星期日,请在工作日添加一个

    • add one to the temp date
    • 在临时日期添加一个

  12. 临时日期小于结束日期:如果临时日期不是星期六或星期日,请在工作日添加一个临时日期

  13. That's it.

The stepping part at the end can probably be replaced by some other algorithm, but it will never loop for more than 6 days so it's a simple and reasonably efficient solution to the issue of uneven weeks.

最后的步进部分可能会被其他一些算法取代,但它永远不会循环超过6天,因此它是一个简单而合理有效的解决不平衡周数的问题。

Some consequences of the above:

以上的一些后果:

  1. Monday to Friday is 4 business days
  2. 周一至周五为4个工作日

  3. Any day to the same day in a different week is an even number of weeks and therefore an even mutiple of 5, e.g. Monday 2 Feb to Monday 9 Feb and Sunday 1 Feb to Sunday 8 Feb are 5 business days
  4. 在不同的一周中的同一天的任何一天是偶数周,因此甚至多达5周,例如2月2日星期一至2月9日星期一和2月1日星期日至2月8日星期日是5个工作日

  5. Friday 6 Feb to Sunday 7 Feb is zero business days
  6. 2月6日周五至2月7日周日为零工作日

  7. Friday 6 Feb to Monday 9 Feb is one business day
  8. 2月6日星期五至2月9日星期一是一个工作日

  9. Sunday 8 Feb to: Sunday 15 Feb, Sat 14 Feb and Fri 13 Feb are all 5 business days
  10. 2月8日星期日至2月15日星期日,2月14日星期六和2月13日星期五均为5个工作日

Here's the code:

这是代码:

// Expects start date to be before end date// start and end are Date objectsfunction dateDifference(start, end) {  // Copy date objects so don't modify originals  var s = new Date(+start);  var e = new Date(+end);  // Set time to midday to avoid dalight saving and browser quirks  s.setHours(12,0,0,0);  e.setHours(12,0,0,0);  // Get the difference in whole days  var totalDays = Math.round((e - s) / 8.64e7);  // Get the difference in whole weeks  var wholeWeeks = totalDays / 7 | 0;  // Estimate business days as number of whole weeks * 5  var days = wholeWeeks * 5;  // If not even number of weeks, calc remaining weekend days  if (totalDays % 7) {    s.setDate(s.getDate() + wholeWeeks * 7);    while (s < e) {      s.setDate(s.getDate() + 1);      // If day isn't a Sunday or Saturday, add to business days      if (s.getDay() != 0 && s.getDay() != 6) {        ++days;      }    }  }  return days;}

Dunno how it compares to jfriend00's answer or the code you referenced, if you want the period to be inclusive, just add one if the start or end date are a business day.

Dunno如何与jfriend00的答案或您引用的代码进行比较,如果您希望期间具有包容性,只需在开始日期或结束日期为工作日时添加一个。

#2


2  

Here's a simple function to calculate the number of business days between two date objects. As designed, it does not count the start day, but does count the end day so if you give it a date on a Tuesday of one week and a Tuesday of the next week, it will return 5 business days. This does not account for holidays, but does work properly across daylight savings changes.

这是一个计算两个日期对象之间工作日数的简单函数。按照设计,它不计算开始日期,但会计算结束日期,因此如果您在一周的星期二和下周的星期二给它一个日期,它将返回5个工作日。这不考虑假期,但可以在夏令时更改中正常工作。

function calcBusinessDays(start, end) {    // This makes no effort to account for holidays    // Counts end day, does not count start day    // make copies we can normalize without changing passed in objects        var start = new Date(start);    var end = new Date(end);    // initial total    var totalBusinessDays = 0;    // normalize both start and end to beginning of the day    start.setHours(0,0,0,0);    end.setHours(0,0,0,0);    var current = new Date(start);    current.setDate(current.getDate() + 1);    var day;    // loop through each day, checking    while (current <= end) {        day = current.getDay();        if (day >= 1 && day <= 5) {            ++totalBusinessDays;        }        current.setDate(current.getDate() + 1);    }    return totalBusinessDays;}

And, the jQuery + jQueryUI code for a demo:

并且,演示的jQuery + jQueryUI代码:

// make both input fields into date pickers$("#startDate, #endDate").datepicker();// process click to calculate the difference between the two days$("#calc").click(function(e) {    var diff = calcBusinessDays(        $("#startDate").datepicker("getDate"),         $("#endDate").datepicker("getDate")    );    $("#diff").html(diff);});

And, here's a simple demo built with the date picker in jQueryUI: http://jsfiddle.net/jfriend00/z1txs10d/

而且,这是一个使用jQueryUI中的日期选择器构建的简单演示:http://jsfiddle.net/jfriend00/z1txs10d/

#3


1  

@RobG has given an excellent algorithm to separate business days from weekends. I think the only problem is if the starting days is a weekend, Saturday or Sunday, then the no of working days/weekends will one less.

@RobG提供了一个很好的算法,可以将工作日与周末分开。我认为唯一的问题是,如果开始的日子是周末,周六或周日,那么工作日/周末的数量会减少一个。

Corrected code is below.

更正后的代码如下。

function dateDifference(start, end) {  // Copy date objects so don't modify originals  var s = new Date(start);  var e = new Date(end);    var addOneMoreDay = 0;    if( s.getDay() == 0 || s.getDay() == 6 ) {    addOneMoreDay = 1;  }  // Set time to midday to avoid dalight saving and browser quirks  s.setHours(12,0,0,0);  e.setHours(12,0,0,0);  // Get the difference in whole days  var totalDays = Math.round((e - s) / 8.64e7);  // Get the difference in whole weeks  var wholeWeeks = totalDays / 7 | 0;  // Estimate business days as number of whole weeks * 5  var days = wholeWeeks * 5;  // If not even number of weeks, calc remaining weekend days  if (totalDays % 7) {    s.setDate(s.getDate() + wholeWeeks * 7);    while (s < e) {      s.setDate(s.getDate() + 1);      // If day isn't a Sunday or Saturday, add to business days      if (s.getDay() != 0 && s.getDay() != 6) {        ++days;      }      //s.setDate(s.getDate() + 1);    }  }  var weekEndDays = totalDays - days + addOneMoreDay;  return weekEndDays;}

JSFiddle link is https://jsfiddle.net/ykxj4k09/2/

JSFiddle链接是https://jsfiddle.net/ykxj4k09/2/

#4


0  

First Get the Number of Days in a month

首先获取一个月内的天数

     totalDays(month, year) {        return new Date(year, month, 0).getDate();     }

Then Get No Of Working Days In A Month By removing Saturday and Sunday

然后通过删除星期六和星期日获得一个月的工作日

  totalWorkdays() {     var d = new Date(); // to know present date     var m = d.getMonth() + 1; // to know present month     var y = d.getFullYear(); // to knoow present year     var td = this.totalDays(m, y);// to get no of days in a month     for (var i = 1; i <= td; i++) {          var s = new Date(y, m - 1, i);        if (s.getDay() != 0 && s.getDay() != 6) {           this.workDays.push(s.getDate());// working days        }else {           this.totalWeekDays.push(s.getDate());//week days         }      }      this.totalWorkingDays = this.workDays.length; }

#1


9  

When determining the number of days between two dates, there are lots of decisions to be made about what is a day. For example, the period 1 Feb to 2 Feb is generally one day, so 1 Feb to 1 Feb is zero days.

在确定两个日期之间的天数时,需要做出很多关于一天的决定。例如,2月1日至2月2日期间通常为一天,因此2月1日至2月1日为零天。

When adding the complexity of counting only business days, things get a lot tougher. E.g. Monday 2 Feb 2015 to Friday 6 February is 4 elapsed days (Monday to Tuesday is 1, Monday to Wednesday is 2, etc.), however the expression "Monday to Friday" is generally viewed as 5 business days and the duration Mon 2 Feb to Sat 7 Feb should also be 4 business days, but Sunday to Saturday should be 5.

当增加仅计算工作日计算的复杂性时,事情变得更加艰难。例如。 2015年2月2日星期一至2月6日星期五是4天过去了(星期一到星期二是1,星期一到星期三是2等),但是“星期一到星期五”这个词通常被视为5个工作日,持续时间为2月2日星期一2月7日星期六也应该是4个工作日,但星期日到星期六应该是5个工作日。

So here's my algorithm:

所以这是我的算法:

  1. Get the total number of whole days between the two dates
  2. 获取两个日期之间的总天数

  3. Divide by 7 to get the number of whole weeks
  4. 除以7得到整周的数量

  5. Multiply the number of weeks by two to get the number of weekend days
  6. 将周数乘以2得到周末天数

  7. Subtract the number of weekend days from the whole to get business days
  8. 从整体中减去周末天数以获得工作日

  9. If the number of total days is not an even number of weeks, add the numbe of weeks * 7 to the start date to get a temp date
  10. 如果总天数不是偶数周数,请将周数* 7添加到开始日期以获取临时日期

  11. While the temp date is less than the end date:
    • if the temp date is not a Saturday or Sunday, add one the business days
    • 如果临时日期不是星期六或星期日,请在工作日添加一个

    • add one to the temp date
    • 在临时日期添加一个

  12. 临时日期小于结束日期:如果临时日期不是星期六或星期日,请在工作日添加一个临时日期

  13. That's it.

The stepping part at the end can probably be replaced by some other algorithm, but it will never loop for more than 6 days so it's a simple and reasonably efficient solution to the issue of uneven weeks.

最后的步进部分可能会被其他一些算法取代,但它永远不会循环超过6天,因此它是一个简单而合理有效的解决不平衡周数的问题。

Some consequences of the above:

以上的一些后果:

  1. Monday to Friday is 4 business days
  2. 周一至周五为4个工作日

  3. Any day to the same day in a different week is an even number of weeks and therefore an even mutiple of 5, e.g. Monday 2 Feb to Monday 9 Feb and Sunday 1 Feb to Sunday 8 Feb are 5 business days
  4. 在不同的一周中的同一天的任何一天是偶数周,因此甚至多达5周,例如2月2日星期一至2月9日星期一和2月1日星期日至2月8日星期日是5个工作日

  5. Friday 6 Feb to Sunday 7 Feb is zero business days
  6. 2月6日周五至2月7日周日为零工作日

  7. Friday 6 Feb to Monday 9 Feb is one business day
  8. 2月6日星期五至2月9日星期一是一个工作日

  9. Sunday 8 Feb to: Sunday 15 Feb, Sat 14 Feb and Fri 13 Feb are all 5 business days
  10. 2月8日星期日至2月15日星期日,2月14日星期六和2月13日星期五均为5个工作日

Here's the code:

这是代码:

// Expects start date to be before end date// start and end are Date objectsfunction dateDifference(start, end) {  // Copy date objects so don't modify originals  var s = new Date(+start);  var e = new Date(+end);  // Set time to midday to avoid dalight saving and browser quirks  s.setHours(12,0,0,0);  e.setHours(12,0,0,0);  // Get the difference in whole days  var totalDays = Math.round((e - s) / 8.64e7);  // Get the difference in whole weeks  var wholeWeeks = totalDays / 7 | 0;  // Estimate business days as number of whole weeks * 5  var days = wholeWeeks * 5;  // If not even number of weeks, calc remaining weekend days  if (totalDays % 7) {    s.setDate(s.getDate() + wholeWeeks * 7);    while (s < e) {      s.setDate(s.getDate() + 1);      // If day isn't a Sunday or Saturday, add to business days      if (s.getDay() != 0 && s.getDay() != 6) {        ++days;      }    }  }  return days;}

Dunno how it compares to jfriend00's answer or the code you referenced, if you want the period to be inclusive, just add one if the start or end date are a business day.

Dunno如何与jfriend00的答案或您引用的代码进行比较,如果您希望期间具有包容性,只需在开始日期或结束日期为工作日时添加一个。

#2


2  

Here's a simple function to calculate the number of business days between two date objects. As designed, it does not count the start day, but does count the end day so if you give it a date on a Tuesday of one week and a Tuesday of the next week, it will return 5 business days. This does not account for holidays, but does work properly across daylight savings changes.

这是一个计算两个日期对象之间工作日数的简单函数。按照设计,它不计算开始日期,但会计算结束日期,因此如果您在一周的星期二和下周的星期二给它一个日期,它将返回5个工作日。这不考虑假期,但可以在夏令时更改中正常工作。

function calcBusinessDays(start, end) {    // This makes no effort to account for holidays    // Counts end day, does not count start day    // make copies we can normalize without changing passed in objects        var start = new Date(start);    var end = new Date(end);    // initial total    var totalBusinessDays = 0;    // normalize both start and end to beginning of the day    start.setHours(0,0,0,0);    end.setHours(0,0,0,0);    var current = new Date(start);    current.setDate(current.getDate() + 1);    var day;    // loop through each day, checking    while (current <= end) {        day = current.getDay();        if (day >= 1 && day <= 5) {            ++totalBusinessDays;        }        current.setDate(current.getDate() + 1);    }    return totalBusinessDays;}

And, the jQuery + jQueryUI code for a demo:

并且,演示的jQuery + jQueryUI代码:

// make both input fields into date pickers$("#startDate, #endDate").datepicker();// process click to calculate the difference between the two days$("#calc").click(function(e) {    var diff = calcBusinessDays(        $("#startDate").datepicker("getDate"),         $("#endDate").datepicker("getDate")    );    $("#diff").html(diff);});

And, here's a simple demo built with the date picker in jQueryUI: http://jsfiddle.net/jfriend00/z1txs10d/

而且,这是一个使用jQueryUI中的日期选择器构建的简单演示:http://jsfiddle.net/jfriend00/z1txs10d/

#3


1  

@RobG has given an excellent algorithm to separate business days from weekends. I think the only problem is if the starting days is a weekend, Saturday or Sunday, then the no of working days/weekends will one less.

@RobG提供了一个很好的算法,可以将工作日与周末分开。我认为唯一的问题是,如果开始的日子是周末,周六或周日,那么工作日/周末的数量会减少一个。

Corrected code is below.

更正后的代码如下。

function dateDifference(start, end) {  // Copy date objects so don't modify originals  var s = new Date(start);  var e = new Date(end);    var addOneMoreDay = 0;    if( s.getDay() == 0 || s.getDay() == 6 ) {    addOneMoreDay = 1;  }  // Set time to midday to avoid dalight saving and browser quirks  s.setHours(12,0,0,0);  e.setHours(12,0,0,0);  // Get the difference in whole days  var totalDays = Math.round((e - s) / 8.64e7);  // Get the difference in whole weeks  var wholeWeeks = totalDays / 7 | 0;  // Estimate business days as number of whole weeks * 5  var days = wholeWeeks * 5;  // If not even number of weeks, calc remaining weekend days  if (totalDays % 7) {    s.setDate(s.getDate() + wholeWeeks * 7);    while (s < e) {      s.setDate(s.getDate() + 1);      // If day isn't a Sunday or Saturday, add to business days      if (s.getDay() != 0 && s.getDay() != 6) {        ++days;      }      //s.setDate(s.getDate() + 1);    }  }  var weekEndDays = totalDays - days + addOneMoreDay;  return weekEndDays;}

JSFiddle link is https://jsfiddle.net/ykxj4k09/2/

JSFiddle链接是https://jsfiddle.net/ykxj4k09/2/

#4


0  

First Get the Number of Days in a month

首先获取一个月内的天数

     totalDays(month, year) {        return new Date(year, month, 0).getDate();     }

Then Get No Of Working Days In A Month By removing Saturday and Sunday

然后通过删除星期六和星期日获得一个月的工作日

  totalWorkdays() {     var d = new Date(); // to know present date     var m = d.getMonth() + 1; // to know present month     var y = d.getFullYear(); // to knoow present year     var td = this.totalDays(m, y);// to get no of days in a month     for (var i = 1; i <= td; i++) {          var s = new Date(y, m - 1, i);        if (s.getDay() != 0 && s.getDay() != 6) {           this.workDays.push(s.getDate());// working days        }else {           this.totalWeekDays.push(s.getDate());//week days         }      }      this.totalWorkingDays = this.workDays.length; }