Skip to content

Instantly share code, notes, and snippets.

@sebasbad
Last active February 20, 2019 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebasbad/a1527e1e78d558a819e85176cde3f3b7 to your computer and use it in GitHub Desktop.
Save sebasbad/a1527e1e78d558a819e85176cde3f3b7 to your computer and use it in GitHub Desktop.
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