VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-get-last-day-of-previous-month-from-date-in-momentjs/

⇱ How to Get Last Day of Previous Month From Date in Moment.JS? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Get Last Day of Previous Month From Date in Moment.JS?

Last Updated : 26 Aug, 2024

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 moment

Below 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.

Output:

👁 subtract-start
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.

Output:

👁 sub-start
Output
Comment
Article Tags: