Home > Enterprise >  Get weekday list between two dates? JavaScript
Get weekday list between two dates? JavaScript

Time:01-20

How to get weekday list between two dates? I need javaScript function for that. (date-fns library function also is Ok) as e example

getWeekDayList('2022-01-10', '2022-01-20');

function getWeekDayList(startDate, endDate){
        //Output should be week days only
          2022-01-10
          2022-01-11
          2022-01-12
          2022-01-13
          2022-01-14
          2022-01-17
          2022-01-18
          2022-01-19
          2022-01-20
}

CodePudding user response:

You can use a for loop to loop through each date between the start and end date, then use Date.getDay to get the day of the week and ignore the dates that are not a weekday.

function getWeekDayList(startDate, endDate) {
  let days = []
  let end = new Date(endDate)
  for (let start = new Date(startDate); start <= end; start.setDate(start.getDate()   1)) {
    let day = start.getDay();
    if (day != 6 && day != 0) {
      days.push(new Date(start));
    }
  }
  return days;
}

const result = getWeekDayList('2022-01-10', '2022-01-20')

console.log(result.map(e => e.toLocaleString('en-US', {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })))

  •  Tags:  
  • Related