Find total number of Sundays between two dates in JavaScript
Lets say we want to find out total number of Sundays between two dates. It could be any days of the week. Our use case was we wanted to get the date differences in days excluding Sundays.
Function definition
function getSundayCountBetweenDates(startDate, endDate){ var totalSundays = 0; for (var i = startDate; i <= endDate; i.setDate(i.getDate()+1)){ if (i.getDay() == 0) totalSundays++; } return totalSundays; }
Function calling
var startFrom = "12/15/2018 00:00:00"; var startDate = new Date(startFrom); var endDate = new Date(); var sundayCnt = getSundayCountBetweenDates(startDate, endDate); console.log(sundayCnt);
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 Sundays. The getDay method returns 0 for Sundays and as follows:
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
We increment the counter if it's Sunday. Finally we return the total count.