如何确定周六和周日的数字是在java脚本中的两个日期之间

Sri*_*ini 5 javascript

我有以下要求我有两个日期我需要找到星期六和星期日将如何进入日期
1:02
/ 06/2011 日期2:02/07/2011
10天是周末
谢谢Srini

Mat*_*att 9

O(1)解决方案没有循环:

function countWeekendDays( d0, d1 )
{
  var ndays = 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
  var nsaturdays = Math.floor( (d0.getDay()+ndays) / 7 );
  return 2*nsaturdays + (d0.getDay()==0) - (d1.getDay()==6);
}
Run Code Online (Sandbox Code Playgroud)

的jsfiddle


Bre*_*ett 5

编辑计算周末天数而不是周末数.http://jsfiddle.net/bRgUq/3/

function CalculateWeekendDays(fromDate, toDate){
    var weekendDayCount = 0;

    while(fromDate < toDate){
        fromDate.setDate(fromDate.getDate() + 1);
        if(fromDate.getDay() === 0 || fromDate.getDay() == 6){
            ++weekendDayCount ;
        }
    }

    return weekendDayCount ;
}

console.log(CalculateWeekendDays(new Date(2011, 6, 2), new Date(2011, 7, 2)));
Run Code Online (Sandbox Code Playgroud)


ale*_*lex 1

根据您的日期,它们不是美国格式(至少在它们之间有 10 个周末的情况下不是)。您可以通过以下方式获取美国格式的文件:

var chunks = str.split('/');
str = [chunks[1], chunks[0], chunks[2]].join('/');
Run Code Online (Sandbox Code Playgroud)

此代码循环遍历日期之间的每一天,如果该天是星期六或星期日,则递增计数器。

var start = new Date('06/02/2011'),
    finish = new Date('07/02/2011'),
    dayMilliseconds = 1000 * 60 * 60 * 24;

var weekendDays = 0;

while (start <= finish) {
    var day = start.getDay()
    if (day == 0 || day == 6) {
        weekendDays++;
    }
    start = new Date(+start + dayMilliseconds);
}
Run Code Online (Sandbox Code Playgroud)

js小提琴