简体   繁体   中英

How get list of days in a week that exist in some date range (Javascript)

Hello I need to define existing days in some date range. I don't wont to make loop from start to end dates and use like here http://www.w3schools.com/jsref/jsref_getday.asp Is it possible to calculate it some how ?

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;
}

And testing in the js console:

> 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"]
 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);
    }

I think it is ok. What do you think ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM