You can get the last day of the month, then subtract the day number, e.g.
/* @param {number|string} year - year to use
** @param {number|string} month - calendar month number
** @returns {Date} last Sunday for month in given year
*/
function getLastSunday(year, month) {
let d = new Date(year, month, 0);
d.setDate(d.getDate() - d.getDay());
return d;
}
// Get all last Sundays for current year
for (var y=new Date().getFullYear(), i=1; i<=12; i++) {
console.log(getLastSunday(y, i).toString());
}
Because ECMAScript month numbers are zero based, using the calendar month number in the Date constructor gives the next month, so 8 for August is treated as 9 for September. Setting the day to 0 makes it one day before the 1st so September 0 is August 31.
Similarly, the day numbers are 0 to 6 for Sunday to Saturday, so if the date isn't a Sunday, subtracting the day number moves the date to the previous Sunday.
Near future…
There is a new Temporal object in development that seeks to make this stuff a bit easier. A function to get the last Sunday of a month might be:
/**
* Returns last Sunday of month
*
* @param {Temporal.YearMonth} queryMonth - YearMonth to get last Sunday of
* @returns {Temporal.Date} for last Sunday of queried month
*/
function getLastSunday(queryMonth) {
let lastOfMonth = queryMonth.toDateOnDay(queryMonth.daysInMonth);
return lastOfMonth.minus({days: lastOfMonth.dayOfWeek % 7});
}
// As a Temporal.Date
getLastSunday(Temporal.YearMonth.from('2020-08'));
// As a string like Sun, Aug 30
getLastSunday(Temporal.YearMonth.from('2020-08')).toLocaleString('en', {
weekday: 'short',
day: '2-digit',
month: 'short'
});
Unfortunately it relies on the Intl object for formatting, so there will still be a need for formatting (and parsing) libraries. It would be nice if it included a simple formatter using one of the many token sets currently in use.