如何获取某个日期范围内存在的一周中的天数列表(Javascript)

时间:2013-01-24 07:51:37

标签: javascript

您好我需要在某个日期范围内定义现有天数。 我不会在开始到结束日期之间进行循环,并像这里一样使用http://www.w3schools.com/jsref/jsref_getday.asp 有可能计算一下吗?

2 个答案:

答案 0 :(得分:3)

function getDays(earlierDate, laterDate) {
  var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
  var elapsedDays = (laterDate - earlierDate) / 1000 / 60 / 60 / 24;
  if (elapsedDays < 7) {
    var dayArray = [];
    for (i = 0; i <= elapsedDays; i++) {
        dayArray.push(dayNames[(earlierDate.getDay()+i) % 7]);
    }
    return dayArray;
  }
  return dayNames;
}

在js控制台中测试:

> getDays(new Date("03-01-2012"), new Date("03-01-2012"));
["Thursday"]
> getDays(new Date("03-01-2012"), new Date("03-05-2012"));
["Thursday", "Friday", "Saturday", "Sunday", "Monday"]
> getDays(new Date("03-01-2012"), new Date("03-05-2013"));
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

答案 1 :(得分:0)

 var sevenDaysInMS = 604800000;
    if (new Date(dTo - dFrom).getTime() >= sevenDaysInMS) {
        $('.day_hid').attr(attrUnaviableDay, "true");
    } else {
        var dt = dFrom;
        do {
            var day = dt.getDay();
            ActivateDaySelector(day);
            dt.setDate(dt.getDate() + 1);
        } while (dt <= dTo);
    }

我认为没关系。你觉得怎么样?