I am trying to get the nth day of the week - for example, the second Sunday of the month in which a certain date falls.
For example, if the date is August 24, 2015, I would like to do this:
nthDayOfMonth(0, 2, new Date(2015, 7, 24))
and receive on August 9, 2015 (2nd Sunday of August). Then I would like to add a month to the date, call the function again and get September 13, 2015 (2nd Sunday of September).
For some reason, the code below does not work.
What am I missing?
function nthDayOfMonth(day, n, date) {
console.log(day);
console.log(n);
var count = 0;
var idate = new Date(date);
idate.setDate(1);
while ((count) < n) {
idate.setDate(idate.getDate() + 1);
if (idate.getDay() == day) {
count++;
}
}
return idate;
}
source
share