2

Hi guys I have implemented following for weekly and fortnightly but I need to implement it for monthly using momentjs for below specific rerequirment

Possible payment frequencies are: ● Weekly ● Monthly - The same day every month (e.g. 5th Mar, 5th April, 5th May) For monthly frequency, if the start date of a line item doesn’t exist in some months, we need to have the next payment on the closest day in that month. For example, a lease with payment frequency of monthly starting on 31st August cannot have the next payment on 31st September because 31st September doesn’t exist. Therefore we will have the next payment on the 30th September, the payment after that will be 31st October, reverting back to the original day of the month.

2 Answers2

0

You could use moment().endOf(String) to check for the last day in the current month, see docs https://momentjs.com/docs/#/manipulating/end-of/

Also check this answer Moment JS start and end of given month

serban
  • 48
  • 5
0

You can get the payment day for each month using vanilla JavaScript as well, by creating a Date object with a monthIndex of the desired monthIndex + 1 and a day of 0 if the number of days in that month are less than the payment day.

We can use Array.from() and Array.map() to create an array of the lease payment dates:

   
// 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)))
}
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40