Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get weekdays between two specific weekdays

How can I get all weekday names between 2 weekdays as parameters? It should also return accurately when it get past the 7 days.

My week format is:

'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'

Example and expected output below. Thanks

function day(first, last) {
  var day = new Date();
  var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

  for (i = 0; i < 14; i++) {
    console.log(week[(day.getDay() + 1 + i) % 7]);
  }

}

day('Tuesday', 'Thursday'); // output should be "Tuesday, Wednesday, Thursday"
day('Friday', 'Tuesday'); // output should be "Friday, Saturday, Sunday, Monday, Tuesday
day('Saturday', 'Monday'); // output should be "Saturday, Sunday, Monday"
like image 573
marknt15 Avatar asked Sep 02 '25 16:09

marknt15


1 Answers

You could manipulate the array to avoid using loops. Code is commented for clarity.

function day(first, last) {
  var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

  var firstIndex = week.indexOf(first);          //Find first day
  week = week.concat(week.splice(0,firstIndex)); //Shift array so that first day is index 0
  var lastIndex = week.indexOf(last);            //Find last day
  return week.slice(0,lastIndex+1);              //Cut from first day to last day
}

console.log(day('Tuesday', 'Thursday'));
console.log(day('Friday', 'Tuesday'));
console.log(day('Saturday', 'Monday'));
like image 197
Tyler Roper Avatar answered Sep 05 '25 08:09

Tyler Roper