Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count certain days of the week between two dates
// https://stackoverflow.com/questions/25562173/calculate-number-of-specific-weekdays-between-dates
// days is an array of weekdays: 0 is Sunday, ..., 6 is Saturday
function countCertainDays( days, d0, d1 ) {
var ndays = 1 + Math.round((d1-d0)/(24*3600*1000));
var sum = function(a,b) {
return a + Math.floor( ( ndays + (d0.getDay()+6-b) % 7 ) / 7 ); };
return days.reduce(sum,0);
}
// Feb 5 2018 - Nov 18 2018mon
var startDate = new Date(2018, 2, 5)
var endDate = new Date(2018, 11, 18)
var mondays = countCertainDays([1], startDate, endDate)
var tuesdays = countCertainDays([2], startDate, endDate)
var wednsdays = countCertainDays([3], startDate, endDate)
var thursdays = countCertainDays([4], startDate, endDate)
var fridays = countCertainDays([5], startDate, endDate)
var saturdays = countCertainDays([6], startDate, endDate)
var sundays = countCertainDays([7], startDate, endDate)
var daysOfWeekCountMondayToSunday = [mondays, tuesdays, wednsdays, thursdays, fridays, saturdays, sundays]
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,1)) // 1
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,2)) // 1
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,3)) // 2
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,4)) // 2
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,5)) // 3
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,6)) // 3
countCertainDays([1,3,5],new Date(2014,8,1),new Date(2014,8,7)) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment