Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Get Last Day of Previous Month from Date in Moment.JS?
When working with dates in JavaScript, it's common to need specific dates for calculations or validations. One such situation is determining the last day of the previous month from a given date. In this article, we'll learn how to get the last day of the previous month using Moment.js.
Prerequisite
Moment.js: Moment.js is a popular JavaScript library used to parse, validate, manipulate, and display dates and times in JavaScript.
You can install Moment.js in your project via npm:
npm install moment
Approaches to Get Last Day of Previous Month
Below are two 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 most straightforward approach. We use subtract(1, 'months') to move back to the previous month, then endOf('month') to get the last day of that month.
Example
const moment = require('moment');
let date = moment('2024-03-15'); // Given date
let lastDay = date.clone().subtract(1, 'months').endOf('month');
console.log('Original date:', date.format('YYYY-MM-DD'));
console.log('Last day of previous month:', lastDay.format('YYYY-MM-DD'));
Original date: 2024-03-15 Last day of previous month: 2024-02-29
The input date is March 15, 2024. This method moves one month back to February 15, 2024, then sets it to the last day of February, which is February 29, 2024 (leap year).
Using startOf() and subtract() Methods
This approach first moves to the first day of the current month using startOf('month'), then subtracts one day to get the last day of the previous month.
Example
const moment = require('moment');
let date = moment('2024-03-15'); // Given date
let lastDay = date.clone().startOf('month').subtract(1, 'days');
console.log('Original date:', date.format('YYYY-MM-DD'));
console.log('Last day of previous month:', lastDay.format('YYYY-MM-DD'));
Original date: 2024-03-15 Last day of previous month: 2024-02-29
The input date is March 15, 2024. This method first moves to March 1, 2024, then subtracts one day to get February 29, 2024.
Comparison
| Method | Steps | Readability | Performance |
|---|---|---|---|
subtract().endOf() |
2 operations | More intuitive | Slightly faster |
startOf().subtract() |
2 operations | Less intuitive | Slightly slower |
Important Note
Always use clone() when chaining Moment.js methods to avoid mutating the original date object. This ensures your original date remains unchanged.
Conclusion
Both methods effectively get the last day of the previous month. The subtract().endOf() approach is more intuitive and recommended for better code readability.
