如何在Javascript中找到两个日期之间的给定天数?

时间:2013-05-14 17:52:02

标签: javascript date

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

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

由于

更新

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

2 个答案:

答案 0 :(得分: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 + 1dayOfWeek1 ... dayOfWeek1 + (6 - extraDays)

您有weeks + 1 + extraDaysdayOfWeek1 + (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.
}

答案 1 :(得分: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.
    }
}