如何在javascript中获取两个不同日期之间的工作日

时间:2014-08-28 13:47:02

标签: javascript date

在这里,我需要一种方法来找出两个日期之间的工作日。如果我提供两个日期,例如' 2014-08-28'并且' 2014-08-30',它应该返回['Friday','Saturday']

var d = new Date();
var weekday = new Array(7);
weekday[0]=  "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()]; 

如何使用.getDay()

1 个答案:

答案 0 :(得分:0)

你需要编写一些函数,最重要的是,使用Date.parse将日期转换为ms并在日期之间进行数学运算。解决方案如下。有关工作代码,请参阅jsFiddle。 demo

var days = 3;
var msPerDay = 1000*60*60*24;


var nextDay = function ( day , dayAfter ) {
    return Date.parse(day) + (msPerDay*dayAfter);
}

var daysBetween = function ( from, to ) {
  return ((Date.parse(to) - Date.parse(from))/msPerDay) - 1 ;
}


var d1 = new Date();
var d2 = new Date( nextDay( d1, days ));

var weekday = new Array(7);
weekday[0]=  "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";


var getInbetweenWeekdays = function () {
   var weekDays = [];
   for (var i = 0 ; i < daysBetween( d1, d2 ); i++ ) {
       weekDays.push(weekday[new Date( nextDay( d1, i + 1 ) ).getDay()]);
   }

   return weekDays;
}



alert(getInbetweenWeekdays());

稍微详细说明,添加适当的吸气剂,你会很好,但是你会得到漂移。