如何计算两个日期之间的星期天数

vis*_*huB 5 javascript

我试过下面的JS:

var start = new Date("25-05-2016");
var finish = new Date("31-05-2016");
var dayMilliseconds = 1000 * 60 * 60 * 24;
var weekendDays = 0;
while (start <= finish) {
  var day = start.getDay()
  if (day == 0) {
    weekendDays++;
  }
  start = new Date(+start + dayMilliseconds);
}
alert(weekendDays);
Run Code Online (Sandbox Code Playgroud)

但是,它给出了错误的输出。

我需要获得两个日期之间星期日总数

spl*_*h58 5

您使用了不正确的日期格式。如果初始化日期如下,它将起作用:

var start = new Date("2016-05-25");
var finish = new Date("2016-05-31");
Run Code Online (Sandbox Code Playgroud)


Que*_*Roy 5

您的日期格式错误。日期的字符串格式为"yyyy-mm-dd". 浏览此处获取更多信息。

此外,循环间隔的每一天效率非常低。您可以尝试以下方法。

function getNumberOfWeekDays(start, end, dayNum){
  // Sunday's num is 0 with Date.prototype.getDay.
  dayNum = dayNum || 0;
  // Calculate the number of days between start and end.
  var daysInInterval = Math.ceil((end.getTime() - start.getTime()) / (1000 * 3600 * 24));
  // Calculate the nb of days before the next target day (e.g. next Sunday after start).
  var toNextTargetDay = (7 + dayNum - start.getDay()) % 7;
  // Calculate the number of days from the first target day to the end.
  var daysFromFirstTargetDay = Math.max(daysInInterval - toNextTargetDay, 0);
  // Calculate the number of weeks (even partial) from the first target day to the end.
  return Math.ceil(daysFromFirstTargetDay / 7);
}


var start = new Date("2016-05-25");
var finish = new Date("2016-05-31");

console.log("Start:", start);
console.log("Start's week day num:", start.getDay());
console.log("Finish:", finish);
console.log("Finish's week day num:", finish.getDay());

console.log("Number of Sundays:", getNumberOfWeekDays(start, finish));
Run Code Online (Sandbox Code Playgroud)