jquery - How do I calculate number of given weekday between range using Moment JS? -
how find out how many of given weekday (ex: tuesdays) in date range using moment js , jquery?
i can find number of days using difference: http://momentjs.com/docs/#/displaying/difference/
and know start , end date, feel should possible?
example: how many tuesdays there between march 1st , march 25th?
i came following function seems work given handful of test cases tried:
function weekdaysbetween(d1, d2, isoweekday) { // ensure have valid moment instances d1 = moment(d1); d2 = moment(d2); // figure out how many days advance next // specified weekday (might 0 if d1 // specified weekday). var daystoadd = ((7 + isoweekday) - d1.isoweekday()) % 7; var nexttuesday = d1.clone().add(daystoadd, 'days'); // if passed end date, there must not // of day in given period. if (nexttuesday.isafter(d2)) { return 0; } // otherwise, return whole number of weeks // difference plus 1 day advanced var weeksbetween = d2.diff(nexttuesday, 'weeks'); return weeksbetween + 1; }
you pass in isoweekday
value day trying count. e.g. tuesday, pass in 2
.
sample invocation:
var d1 = moment('2015-03-01'); var d2 = moment('2015-03-25'); console.log('result:', weekdaysbetween(d1, d2, 2)); // => result: 4
wolfram alpha gives same result.
you should add own tests before trusting completely, though.
Comments
Post a Comment