// Get the number of days in a given month...
function getDaysInMonth (year, month) {
return new Date(year, month, 0).getDate();
}
// Create an array of the dates in question
function getPaymentDates(startYear, startMonth, dayOfMonth, termMonths) {
return Array.from({ length: termMonths }, (v, monthOffset) => {
const daysInMonth = getDaysInMonth(startYear, startMonth + monthOffset);
if (dayOfMonth <= daysInMonth) {
return new Date(startYear, startMonth + monthOffset - 1, dayOfMonth)
} else {
// Return the last day of the month
return new Date(startYear, startMonth + monthOffset, 0)
}
});
}
// Log the dates in a convenient format
const options = { year: 'numeric', month: 'numeric', day: 'numeric' }
// Test with some different payment days...
const days = [1,15,30,31];
for(let dom of days) {
console.log(`Payment dates (DOM = ${dom}):`, getPaymentDates(2021, 8, dom, 12).map(d => d.toLocaleDateString([], options)))
}