How do I find out how many of a given weekday (ex: Tuesdays) are in a date range using Moment JS and jQuery?
I can find the number of days using Difference: http://momentjs.com/docs/#/displaying/difference/
And I know the start and end date, so I feel like it should be possible?
Example: How many Tuesdays are there between March 1st and March 25th?
https://github.com/andruhon/moment-weekday-calc does what you need. It calculates specific weekdays in the range, with option to exclude particular days (say public holidays)
Usage:
I came up with the following function that seems to work for the given handful of test cases I tried:
You pass in the
isoWeekday
value for the day you are trying to count. e.g. for Tuesday, pass in2
.Sample invocation:
Wolfram Alpha gives the same result.
You should add your own tests before trusting this completely, though.
if you are like me with a mind that get confused on maths:
If you're trying to find the number of weekdays W (e.g. Monday, Tuesday, …) between the two dates N and M, you can: