English 中文(简体)
两个日期之间的定时差(周末除外)
原标题:Find day difference between two dates (excluding weekend days)

Hi i正在使用jquery-uidatepicker来选定日期和date.js,以便在两个日期之间找到区别。

现在的问题是,我想将周末的计算时间(日间和日间)排除在外。 如何这样做?

例如,用户选择起始日期(2010年8月13日)和截止日期(2010年8月16日)。 自2006年以来 2010年8月14日和2010年8月15日是每周的,而不是总共4天,只需要2天。

这是现在使用的法典:

<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 = 1 + Math.round((enddate1 - startdate1)/day);             

    if(days>0)
    { $("#noofdays").val(days);}
    else
    { $("#noofdays").val(0);}


    });

    </script>
最佳回答

也许其他人可以帮助你将这一职能转换成宗教基金框架......

我发现这一职能here

function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
  var iWeeks, iDateDiff, iAdjust = 0;
  if (dDate2 < dDate1) return -1; // error code if dates transposed
  var iWeekday1 = dDate1.getDay(); // day of week
  var iWeekday2 = dDate2.getDay();
  iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
  iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
  if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend
  iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
  iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;

  // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
  iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)

  if (iWeekday1 < iWeekday2) { //Equal to makes it reduce 5 days
    iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
  } else {
    iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
  }

  iDateDiff -= iAdjust // take into account both days on weekend

  return (iDateDiff + 1); // add 1 because dates are inclusive
}

var date1 = new Date("August 11, 2010 11:13:00");
var date2 = new Date("August 16, 2010 11:13:00");
alert(calcBusinessDays(date1, date2));

## EDITED ##

如果你想用你这样的格式使用:

你的法典将考虑:

function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
  var iWeeks, iDateDiff, iAdjust = 0;
  if (dDate2 < dDate1) return -1; // error code if dates transposed
  var iWeekday1 = dDate1.getDay(); // day of week
  var iWeekday2 = dDate2.getDay();
  iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
  iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
  if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend
  iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
  iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;

  // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
  iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)

  if (iWeekday1 < iWeekday2) { //Equal to makes it reduce 5 days
    iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
  } else {
    iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
  }

  iDateDiff -= iAdjust // take into account both days on weekend

  return (iDateDiff + 1); // add 1 because dates are inclusive
}


$("#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 = new Date(d1);
  var enddate1 = new Date(d2);


  var newstartdate = new Date();
  newstartdate.setFullYear(startdate1.getYear(), startdate1.getMonth(), startdate1.getDay());
  var newenddate = new Date();
  newenddate.setFullYear(enddate1.getYear(), enddate1.getMonth(), enddate1.getDay());
  var days = calcBusinessDays(newstartdate, newenddate);
  if (days > 0) {
    $("#noofdays").val(days);
  } else {
    $("#noofdays").val(0);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>Start Date
 <input type="date" id="startdate" value="2019-03-03"/>
</label>

<label>End Date
 <input type="date" id="enddate" value="2019-03-06"/>
</label>

<label>N. of days
 <output id="noofdays"/>
</label>
问题回答

为此,你请NOT在这些日期之间搜索所有天!

它并不复杂,只看一些明显的假设:

  1. 所有全周都有7天。

  2. 2个周末。

  3. 其中5个为营业日。

证据确凿的结论:

  1. 一切日子都是浪费时间。

  2. 周末到所有一周检查是时间损失。


如果没有令人不解的解释,请让我表明:

function getBusinessDateCount (startDate, endDate) {
    var elapsed, daysBeforeFirstSaturday, daysAfterLastSunday;
    var ifThen = function (a, b, c) {
        return a == b ? c : a;
    };

    elapsed = endDate - startDate;
    elapsed /= 86400000;

    daysBeforeFirstSunday = (7 - startDate.getDay()) % 7;
    daysAfterLastSunday = endDate.getDay();

    elapsed -= (daysBeforeFirstSunday + daysAfterLastSunday);
    elapsed = (elapsed / 7) * 5;
    elapsed += ifThen(daysBeforeFirstSunday - 1, -1, 0) + ifThen(daysAfterLastSunday, 6, 5);

    return Math.ceil(elapsed);
}

function calc() {
  let start = document.querySelector( #startDate ).value,
      end = document.querySelector( #endDate ).value,
      result = getBusinessDateCount(new Date(start), new Date(end));
  document.querySelector( #result ).value = result;
}
Start date: <input type="date" id="startDate" value="2020-01-04"><br>
End date: <input type="date" id="endDate" value="2020-01-06"><br>
<input type="button" onclick="calc()" value="Get business days"><br>
Business days: <input id="result" readonly>

你们可以用任何日期来测试它。

我只想指出,,该法典在2000年至2015年期间消费了0.43 sec。 这比其他一些法典要快得多。

希望有助于......

Nice!

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf())
    date.setDate(date.getDate() + days);
    return date;
}

function getBusinessDatesCount(startDate, endDate) {
    var count = 0;
    var curDate = startDate;
    while (curDate <= endDate) {
        var dayOfWeek = curDate.getDay();
        var isWeekend = (dayOfWeek == 6) || (dayOfWeek == 0); 
        if(!isWeekend)
           count++;
        curDate = curDate.addDays(1);
    }
    return count;
}



//Usage
var startDate = new Date( 7/16/2015 );
var endDate = new Date( 7/20/2015 );
var numOfDays = getBusinessDatesCount(startDate,endDate);
jQuery( div#result ).text(numOfDays);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"/>

That looks like too much work to me. I d rather let the computer do the heavy lifting- //

Date.bizdays= function(d1, d2){
    var bd= 0, dd, incr=d1.getDate();
    while(d1<d2){
        d1.setDate(++incr);
        dd= d1.getDay();
        if(dd%6)++bd;
    }
    return bd;
}

//test

var day1= new Date(2010, 7, 11), day2= new Date(2010, 7, 31);

alert(Date.bizdays(day1, day2))

理解方式,


  1. Actual days = 14
  2. weeks for Actual days = 14/7=2
  3. Weekends per week=2
  4. Total weekends=2*weeks for days

因此,

 $( #EndDate ).on( change , function () {
            var start = $( #StartDate ).datepicker( getDate );
            var end = $( #EndDate ).datepicker( getDate );
            if (start < end) {
                var days = (end - start) / 1000 / 60 / 60 / 24;

                var Weeks=Math.round(days)/7;

                var totalWeekends=Math.round(Weeks)*2;

                var puredays=Math.round(days)-totalWeekends;

                $( #days ).text(Math.round(puredays) + "Working Days");


            }
            else {
alert("");
}

谢谢!

<>Important: 如果启动日期(有时是结束日期)为饱和日,这里的大多数答案实际上不会奏效。 我采取了已接受的答复,并作了修改,以便现在解决这个问题:

    var dateDiff;
    if (dateTo < dateFrom) return -1; // error code if dates transposed
    var dateFromDayOrig = dateFrom.getDay(); // day of week
    var dateToDayOrig = dateTo.getDay();
    var dateFromDay = (dateFromDayOrig == 0) ? 7 : dateFromDayOrig; // change Sunday from 0 to 7
    var dateToDay = (dateToDayOrig == 0) ? 7 : dateToDayOrig;
    dateFromDay = (dateFromDay > 5) ? 5 : dateFromDay; // only count weekdays
    dateToDay = (dateToDay > 5) ? 5 : dateToDay;

    // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
    var weekDifference = Math.floor((dateTo.getTime() - dateFrom.getTime()) / 604800000);

    if (dateFromDay <= dateToDay) {
        dateDiff = (weekDifference * 5) + (dateToDay - dateFromDay);
    } else {
        dateDiff = ((weekDifference + 1) * 5) - (dateFromDay - dateToDay);
    }

    // fix: remove one day if it s saturday or sunday
    if (dateFromDayOrig >= 6 || dateFromDayOrig == 0) {
    dateDiff--;
    }

    return (dateDiff + 1); // add 1 because dates are inclusive

看来,作为解决办法的反应很少。

  • 如果我选择起算日期为2015年11月6日,则该表将“未来年”重新计算。 因此,起始点1和最终结果1可直接转至这一职能。

  • 如果起算日期是星期六或星期天,则该守则将它(i Weekday1)计算为5天。

  • If the end date is Saturday or Sunday, still the code is counting it(iWeekday2) as 5 days. But these 5 days already get counted in the iweeks calculation.
    So instead of
    iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
    iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;

    it should be
    iWeekday1 = (iWeekday1 > 5) ? 0 : iWeekday1; // only count weekdays
    iWeekday2 = (iWeekday2 > 5) ? 0 : iWeekday2;

  • The last IF condition should be executed when start and end date day is same like both are on same day, the date could be different
    if (iWeekday1 <= iWeekday2)

  • The condition that adjusts if both days are weekends can be removed
    iDateDiff -= iAdjust

  • Lastly, the +1 should be done only if start and end date falls on weekdays. Currently, it is adding in both the cases.
    return (iDateDiff + 1);//Add condition to apply only if both days are weekdays

--------------------------

我开始这项工作。 请注意,该职能来自date.js和营业日js(与Gardis Suero相比)。 开始日期 * E/CN.6/2009/1。 16-08-2010年将有4天的休假。

<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>

我做了些什么。

function calcbusinessdays()
{
    for(var c=0,e=0,d=new Date($("#startdate").val()),a=(new Date($("#enddate").val())-d)/864E5;0<=a;a--)
    {
        var b=new Date(d);
        b.setDate(b.getDate()+a);
        1==Math.ceil(b.getDay()%6/6)?c++:e++
    }
    $("#noofdays").html(c)
};

<代码>c为周日,e为周末。

function addDays(date, days) {
    var result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
}
 var currentDate;
                            selectFlixbleDates = [];
                            var monToSatDateFilter=[];
                            currentDate=new Date(date);
                            while(currentDate){
                                console.log("currentDate"+currentDate);
                                if(new Date(currentDate).getDay()!=0){
                                    selectFlixbleDates.push(currentDate)
                                }
                                if(selectFlixbleDates.length==$scope.numberOfDatePick)
                                {

                                    break;
                                }
                                currentDate=addDays(currentDate,1);

                            }
                            for (var i = 0; i < selectFlixbleDates.length; i++) {

                                //  console.log(between[i]);
                                monToSatDateFilter.push((selectFlixbleDates[i].getMonth() + 1) +  /  + selectFlixbleDates[i].getDate() +  /  + selectFlixbleDates[i].getFullYear());

                            }
                            var endDate=monToSatDateFilter.slice(-1).pop();
                            var space =monToSatDateFilter.join( ,  );
                            var sdfs= document.getElementById("maxPicks").value =space;
                            $scope.$apply(function() {
                                $scope.orderEndDate=monToSatDateFilter.slice(-1).pop()
                                $scope.orderStartDate=monToSatDateFilter[0];
                            });
                            document.getElementById("startDateEndDate").innerHTML =$scope.orderStartDate+   TO   +$scope.orderEndDate
                        }  

I have used Angular framework and Moment.js library to implement the solution. My solution covers all the cases.

this.daysInBetween = this.endMoment.diff(this.startMoment,  days ) + 1;
this.weeksInBetween = this.endMoment.diff(this.startMoment,  weeks );
this.weekDays = this.daysInBetween - (this.weeksInBetween * 2);

if ( (this.startMoment.day() === 0 && this.endMoment.day() === 6) ||
 (this.startMoment.day() > this.endMoment.day()) ) {
  // IF ONE WEEKEND WAS MISSED
  this.weekDays-=2;
} else if ( this.startMoment.day() <= this.endMoment.day() &&
( this.startMoment.day() === 0 || this.startMoment.day() === 6 ||
  this.endMoment.day() === 0 || this.endMoment.day() === 6) ) {
  // IF EITHER OF DAYS WAS A WEEKEND
  this.weekDays--;
}

Live Demo: Calculate number of weekdays

I am currently working on a blog to write about my approach to this specific problem. I will post the link to the blog on the comment.

Important: Most answers here don t actually work if the start date (or sometimes the end date) is a saturday or sunday. For example: if your start and end date are

  • Saturday to Sunday or vice versa
  • or Saturday to Saturday
  • or Sunday to Sunday

因此,这里是从已接受的答复中修改的答案。

function calculateBusinessDays(dDate1, dDate2) {

var iWeeks, iDateDiff, iAdjust = 0;
if (dDate2 < dDate1) {
    return -1;
iii

var iWeekday1 = dDate1.getDay();
var iWeekday2 = dDate2.getDay();

iWeekday1 = (iWeekday1 === 0) ? 7 : iWeekday1;
iWeekday2 = (iWeekday2 === 0) ? 7 : iWeekday2;

if (iWeekday1 > 5 && iWeekday2 <= 6) {
    iWeekday1 = 0;
    iAdjust = 1;
iii
iWeekday2 = (iWeekday1 === 0 && iWeekday2 === 6) ? 0 : iWeekday2;

if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1;

iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1;
iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000);

if (iWeeks===0 && iWeekday1===0 && iWeekday2===0 
    && (dDate2.getTime() !== dDate1.getTime()) ) {
    iWeeks = 1;
iii

if (iWeekday1 <= iWeekday2) {
    iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
iii else {
    iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
iii
iDateDiff -= iAdjust
return (iDateDiff + 1);

iii





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签