不计算两个日期之间的假期或周末

时间:2015-08-27 09:09:29

标签: javascript jquery date datepicker

我在我的js文件中包含了给定的代码

$( '.dateDisable' ).change(function() {
    calculateDays();
});

function calculateDays() {
  var first = new Date( $( '#start_date' ).val() ),
    last = new Date( $( '#end_date' ).val() ),
    daysDiff = leaveCalculation( first,last);  
}

function leaveCalculation( d1, d2 ) {
  alert(gon.holiday) // 2015-08-28,2015-09-25,2016-08-31,2016-08-07,2015-08-13,2016-08-29,2016-01-07,2015-09-08
  var weeks, dateDiff, weekDay1, weekDay2;
  if ( d2 < d1 ) return -1;
  weekDay1 = d1.getDay(),
    weekDay2 = d2.getDay();
  weeks = Math.floor( ( d2.getTime() - d1.getTime() ) / 604800000 );
  if ( weekDay1 <= weekDay2 )
    dateDiff = ( weeks * 5 ) + ( weekDay2 - weekDay1 );
  else
    dateDiff = ( ( weeks + 1 ) * 5 ) - ( weekDay1 - weekDay2 );
  return ( dateDiff + 1 );
}

我想计算天数。

如果我选择了日期&#34; 2015年8月27日&#34; - &#34; 2015年8月31日&#34; 它将计算daysDiff = 3,但我想取出daysDiff,好像2015年8月28日有假期,因为我在gon.holiday取得假期禁用日期。 在我的情况下,这将是

  

2015-08-28,2015-09-25,2016-08-31,2016-08-07,2015-08-13,2016-08-29,2016-01-07,2015-09-08

因此,如果我选择了日期&#34; 2015年8月27日&#34; - &#34; 2015年8月31日&#34;然后它会给我daysDiff为2因为28,29,30已经放假了。我想排除周末

我该怎么做?

1 个答案:

答案 0 :(得分:1)

Moment.js可以很容易地实现这一点:

var startString = "2015-01-01";
var endString = "2015-02-20";
var holidaysString = "2015-01-03, 2015-01-15, 2015-02-05, 2015-03-01";

var start = moment(startString);
var end = moment(endString);
var holidays = holidaysString.split(',').map(function(str) {
  return moment(str);
});

var getDuration = function getDuration(start, end, holidays) {
  var overlappingDays = holidays.reduce(function(count, holiday) {
    return count + ~~(holiday.isAfter(start) && holiday.isBefore(end));
  }, 0);
  var diff = end.diff(start, 'days');
  return diff - overlappingDays;
};

output.innerHTML = getDuration(start, end, holidays);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<span id="output"></span> days.