2016-07-26 89 views

回答

1

获得假期阵列实际上可能不是故事中最简单的部分。

无论如何,我会假设你最终会以[ year, month, day ]格式结束日期列表。存储完整的Date对象还有另一种可能性,根据您的导入方法,该对象可能更适合也可能不适合。

下面是一个非常简化,显然是不全面之一:

const holidays = [ 
    [ 2015, 1, 1 ], [ 2015, 1, 19 ], [ 2015, 7, 4 ], [ 2015, 12, 25 ], 
    [ 2016, 1, 1 ], [ 2016, 1, 18 ], [ 2016, 7, 4 ], [ 2016, 12, 25 ], 
    [ 2017, 1, 1 ], [ 2017, 1, 16 ], [ 2017, 7, 4 ], [ 2017, 12, 25 ] 
]; 

这里是一些代码,以帮助您开始:

const holidays = [ 
 
    [ 2015, 1, 1 ], [ 2015, 1, 19 ], [ 2015, 7, 4 ], [ 2015, 12, 25 ], 
 
    [ 2016, 1, 1 ], [ 2016, 1, 18 ], [ 2016, 7, 4 ], [ 2016, 12, 25 ], 
 
    [ 2017, 1, 1 ], [ 2017, 1, 16 ], [ 2017, 7, 4 ], [ 2017, 12, 25 ] 
 
]; 
 

 
function isHoliday(ts) { 
 
    var year = ts.getFullYear(), 
 
     month = ts.getMonth(), 
 
     day = ts.getDate(); 
 

 
    return holidays.some(function(d) { 
 
    return d[0] == year && d[1] == month + 1 && d[2] == day; 
 
    }); 
 
} 
 

 
function getWorkingDays(ts, end) { 
 
    for(var cnt = 0; ts.getTime() <= end.getTime(); ts.setDate(ts.getDate() + 1)) { 
 
    // increment counter if this day is neither a Sunday, 
 
    // nor a Saturday, nor a holiday 
 
    if(ts.getDay() != 0 && ts.getDay() != 6 && !isHoliday(ts)) { 
 
     cnt++; 
 
    } 
 
    } 
 
    return cnt; 
 
} 
 

 
console.log(getWorkingDays(new Date('2015-12-20'), new Date('2016-01-03'))); 
 
console.log(getWorkingDays(new Date('2016-12-20'), new Date('2017-01-03')));