直接上代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>从两个时间段里分别计算出有几天工作日与周末</title> <style type="text/css"> #calculate { background-color: #ff6444; padding: 10px; color: #fff; cursor: pointer; text-align: center; display: inline-block; } </style> </head> <body> <div style="margin-top: 10px;"> <input type="text" id="date1" value="2018-01-21"> <input type="text" id="date2" value="2018-01-31"> <sapn id="calculate">计算</span> </div> <div id="work"></div> <div id="weekend"></div> <script> //获取标签ID的方法 function getId(id) { return document.getElementById(id); } //获取工作日的方法 function getWorkDay(first, last) { //获取开始时间的总毫秒数 first = first.getTime(); //获取结束时间的总毫秒数 last = last.getTime(); var count = 0;//设置一个容器来保存有多少个工作日 if (first <= last) { for (var i = first; i <= last; i += 24 * 3600 * 1000) { var d = new Date(i); if (d.getDay() >= 1 && d.getDay() <= 5) { count++; } } return count; } else { return '输入日期有误'; } } //获取周末的方法 function getWeekendDay(first, last) { first = first.getTime(); last = last.getTime(); var sum = 0; if (first <= last) { for (var i = first; i <= last; i += 24 * 3600 * 1000) { var d = new Date(i); if (d.getDay() == 0 || d.getDay() == 6) { sum++; } } return sum; } else { return '输入日期有误'; } } var calculate = getId('calculate'); calculate.onclick = function() { var date1 = getId('date1').value.split('-'); var date2 = getId('date2').value.split('-'); var d1 = new Date(date1[0], date1[1] - 1, date1[2]); var d2 = new Date(date2[0], date2[1] - 1, date2[2]); var all_day = parseInt(d2.getTime() - d1.getTime()) / (24 * 3600 * 1000); var r = getWorkDay(d1, d2); //工作日 var w = getWeekendDay(d1, d2); //周末 var work = getId('work'); var weekend = getId('weekend'); if (r > 0 && w > 0) { work.innerHTML = '从' + date1[0] + '-' + date1[1] + '-' + date1[2] + '到' + date2[0] + '-' + date2[1] + '-' + date2[2] + '有' + r + '个工作日'; weekend.innerHTML = '从' + date1[0] + '-' + date1[1] + '-' + date1[2] + '到' + date2[0] + '-' + date2[1] + '-' + date2[2] + '有' + w + '个休息日'; } else { work.innerHTML = r; weekend.innerHTML = w; } } </script> </body> </html>