简体   繁体   中英

Get days of week for date range, javascript

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.

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.

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