0

我有两个任意日期,比如说 2012 年 4 月 1 日和 2013 年 1 月 15 日。我想计算这两个日期之间的星期日、星期一、星期二、星期三、星期四、星期五和星期六的数量。

有没有一种万无一失的快速方法来做到这一点而不会削弱用户的 CPU/浏览器?

谢谢

更新

这样做的前提是,对于一周中的任何一天,我们都有一个定义的平均事件数。我们需要计算在一个时间段内发生的事件数量,即使是部分事件(比如周日的 1/2 天将是添加到总数中的事件数量的一半)

4

2 回答 2

2

好的,这是一个可能未经测试的解决方案

date1 = new Date("2012-02-10");
date2 = new Date("2012-03-10");

daysInBetween = (date2.getTime() - date1.getTime())/1000/3600/24;

dayOfTheWeek1 = date1.getDay();

weeks = parseInt(daysInBetween/7, 10);
extraDays = daysInBetween%7;

你有weeks + 1几天dayOfWeek1 ... dayOfWeek1 + (6 - extraDays)

你有weeks + 1 + extraDays几天dayOfWeek1 + (6 - extraDays) ... dayOfWeek1 + 6

请考虑一下,如果dayOfWeek1 === 6那时我假设dayOfWeek1 + 1 === 0

编辑:

多一点代码:

var days = {};
var dayOfTheWeekEnd = dayOfTheWeek1 + 6 - extraDays; // no imagination for names...
if (dayOfTheWeekEnd < 6) {
  if (0 >= dayOfTheWeek1 && 0 <= dayOfTheWeekEnd) {
    days.sunday = weeks + 1;
  } else {
    days.sunday = weeks + 1 + extraDays;
  }
  // etc for the other days, a for loog with an i instead of the 0 would be better.
} else {
  // I have to go the school! I'll edit it later.
  // The idea is that you have to take dayOfTheWeekEnd back to the 0-6 range
  // and check if its after dayOfWeek1 or before dayOfTheWeekEnd, then days.sunday=weeks+1.
}
于 2013-05-14T18:12:02.770 回答
0

想通了...还没有测试过,但我希望它有所帮助。

function(date1, date2) {
   // date1 is assumed to be 12:00:00 am and date2 is actually the date after target at 
   // 12:00:00 am to make the dates inclusive so from the example date1 = 2012/4/1 and
   // date2 = 2013/1/16
   var timeBetween = date2.getTime() - date1.getTime(); //milliseconds between
   var weeks = timeBetween/1000/60/60/24/7;
   var sun = weeks;
   var mon = weeks;
   var tue = weeks;
   var wed = weeks;
   var thu = weeks;
   var fri = weeks;
   var sat = weeks;

   date1.setTime(date1.getTime() + weeks*7*24*60*60*1000); //set the first date to x weeks later
   //if this iterates more than 7 times then something is wrong.
   while(date1.getTime() < date2.getTime()){
       switch(date1.getDay()){
           case 0:
                sun++;
                break;
           case 1:
                mon++;
                break;
           ...
        }
        date1.setTime(date1.getTime() + 1000 * 60 * 60 * 24); //Move date 1 to the next date.
    }
}
于 2013-05-14T18:27:26.060 回答