Find total number of Sundays, Saturdays between two dates in JavaScript

Let’s say we want to find out total number of weekends (Sundays, Saturdays) between two dates. It could be any days of the week. We needed to find out all the weekends count between two dates.

Function definition

function getWeekendCountBetweenDates(startDate, endDate){
   var totalWeekends = 0;
   for (var i = startDate; i <= endDate; i.setDate(i.getDate()+1)){
      if (i.getDay() == 0 || i.getDay() == 1) totalWeekends++;
   return totalWeekends;

Function calling

 var startFrom = "12/15/2018 00:00:00";
 var startDate = new Date(startFrom);
 var endDate = new Date();
 var weekendCnt = getWeekendCountBetweenDates(startDate, endDate);

How the above function work?

In the above function we simply do a loop from start date to end date. Inside the loop we use the get day method to check for Saturdays and Sundays. The getDay method returns 0 for Sundays.

We increment the counter if it's Saturday and Sunday. Finally, we return the total count.