0

I have date range

var fromDate = "2017-01-05";
var toDate = "2017-01-10";

How can I get days of the week that belong to that range?

A range can be different, it can be 2016-12-25 to 2017-05-05, etc. I need to return unique days of the week from provided date range.

The result should be an array of days of weeks. For first range should be ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday"]

Moment can be used if needed, but no jQuery.

snoopy25
  • 1,346
  • 4
  • 12
  • 15
  • 2
    And what have you tried so far? – Eric Aug 16 '17 at 15:23
  • Possible duplicate of [Get difference between 2 dates in JavaScript?](https://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript) – Matus Aug 16 '17 at 15:42
  • I tried this https://jsfiddle.net/snoopy_15/fata6ocb/ but I don't like my solution and of course, it doesn't work well. – snoopy25 Aug 16 '17 at 15:53

1 Answers1

3

Here is one possible solution:

  1. Get all dates from the range.
  2. Loop through the result of step one and return the days of the week:

    var dates = [...]; //(step one result)
    let weekdays = [];
    for (var i = 0; i < dates.length; i++) {
        weekdays.push(moment(dates[i]).day())
    }
    
  3. Make an array of weekdays:

    var wkDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    
  4. Get the day names:

    let weekdaysNamesRange = [];
    for (var i = 0; i < weekdays.length; i++) {
        for (var j = 0; j < wkDays.length; j++) {
            if (weekdays[i] === j) {
               weekdaysNamesRange.push(wkDays[j]);
             }
         }
     }
    
  5. Get unique days:

    var unique = weekdaysNamesRange.filter((item, index, ar) => {
        return weekdaysNamesRange.indexOf(item) === index;
    });
    

I guess there is a better solution, but this is all I came up with.

honk
  • 9,137
  • 11
  • 75
  • 83
snoopy25
  • 1,346
  • 4
  • 12
  • 15