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



Sometimes while working with with dates in JavaScript, it is common to need specific dates for calculations or validations. One such situation is when we are given a date and we have to determine the last day of the previous month. In this article, we are going to learn how we can last day of the Previous Month from Date in Moment.js.

Prerequisite

Moment.js: Moment.js is a popular JavaScript library used to deal with dates. This library is used to modify, parse, validate, manipulate, and display dates and times in JavaScript.

We can install the Moment.js library in the project by adding it via CDN or npm using the following command:

npm install moment

Approaches to Get Last Day of Previous Month from Date

Below are different approaches to get the last day of the previous month from a given date in Moment.js

Using subtract() and endOf() Methods

This is the simple and easy approach to find the last day of the previous month from the date in Moment.js. We first define date using moment(). first we use use subtract(1, 'months') to move back to previous month. Now, use endOf('month') to set the date to the last day of the current month which is now the previous month.

Example

const moment = require('moment');

let date = moment('2024-03-15'); // Given date
let lastDay = date.subtract(1, 'months').endOf('month');

console.log(lastDay.format('YYYY-MM-DD'));

Output

The input date is 15th March 2024. This method first moves one month back gives 15th February 2024. It then sets it to the last day of February which gives 29th February 2024, as 2024 is a leap year.

2024-02-29

Using subtract() and startOf() Methods

This is the most simple approach. In this approach, we first calculate the start of the current month and then move one day backward. We start by defining the date using moment(). Now, we use startOf('month') to shift the date to the first day of the current month. Now, use subtract(1, 'days') to move back to the last day of the previous month. This is not a simple and direct approach but it is still a clear approach.

Example

const moment = require('moment');

let date = moment('2024-03-15'); // Given date
let lastDay = date.startOf('month').subtract(1, 'days'); // Last day of previous month

console.log(lastDay.format('YYYY-MM-DD')); // Output: 2024-02-29

Output

The input date is 15th March 2024. This method first moves input to the first day of March given 1st March 2024. It then moves one day back giving 29th February 2024, which is the last day of February in a leap year.

2024-02-29
Updated on: 2024-12-20T10:11:27+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements