This question already has answers here:
How do I get the number of days between two dates in JavaScript?
                            
                                (37个答案)
                            
                    
                6年前关闭。
        

    

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

有没有一种确定快速的方法来做到这一点而又不损害用户的CPU /浏览器?

谢谢

更新资料

前提是,我们在一周中的任何给定日期都有定义的平均事件数。我们需要计算一个时间段内发生的事件数,即使是部分事件也是如此(例如,周日的1/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.
}

关于javascript - 如何在JavaScript中找到两个日期之间的给定天数? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16549666/

10-12 01:12