To get the last day of the previous month from a given date in Moment.js, you need to adjust the date to the start of the current month and then subtract one day. This approach allows you to accurately find the final day of the previous month regardless of varying month lengths.
Installing Moment.js in Node.js
We have to first install moment.js using the following command in the terminal:
npm install momentBelow are different approaches to get the last day of the previous month from the date in MomentJS:
Using subtract() and endOf() methods
In this approach, we will move the date to the previous month. By using the endOf('month') method, we can find the last day of the month.
Syntax:
moment(date).subtract(1, 'months').endOf('month');Example: This example shows the use of subtract() and endOf() methods.
const moment = require('moment');
const lastDayPrevMonth = moment('2023-08-15').subtract(1, 'months').endOf('month');
console.log(lastDayPrevMonth.format('YYYY-MM-DD'));
Output:

Using subtract() and startOf() methods
In this approach, we start by subtracting one month from the given date, similar to the above approach. After adjusting the date, we use the startOf('month') method to get the first day of that month. To find the last day of the previous month, we simply subtract one day from the first day of the current month. This method allows us to accurately determine the last day of the month.
Syntax:
moment(date).subtract(1, 'months').startOf('month').subtract(1, 'days');Example: This example shows the use of subtract() and startOf() method.
// Importing the moment library
const moment = require('moment');
// Subtract one month from the given date, get
// the start of that month, and then subtract one day
const lastDayPrevMonth = moment('2023-08-15')
.startOf('month').subtract(1, 'days');
// Output
console.log(lastDayPrevMonth.format('YYYY-MM-DD'));
Output:
