![]() |
VOOZH | about |
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.
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:
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.
moment(date).subtract(1, 'months').endOf('month');Example: This example shows the use of subtract() and endOf() methods.
Output:
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.
moment(date).subtract(1, 'months').startOf('month').subtract(1, 'days');Example: This example shows the use of subtract() and startOf() method.
Output: