
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Subtract One Month Using Moment.js
Sometimes while working with with dates in JavaScript, it is common to need specific dates for calculations or validations. In this problem, we are given a date in the form of year-month-date and we have to subtract one month from it. In this article, we are going to learn how we can subtract one month from a given date using Moment.JS.
Prerequisite
- Moment.js: Moment.js is a popular JavaScript library used for dealing with dates. This library is used to modify, parse, validate, manipulate, and display dates and times in JavaScript.
Install Moment.js
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 Subtracting One Month
Using the subtract() Method
In this method, we use the subtract() method in Moment.js which allows us to subtract any time unit from a given date. This method automatically handles edge cases such as subtracting one month from January, leap year, and varying month lengths.
Example
// Import Moment.js const moment = require('moment'); // Define the initial date const initialDate = moment('2024-12-21'); // Subtract one month const newDate = initialDate.subtract(1, 'month'); // Display the result console.log('Initial Date:', initialDate.format('YYYY-MM-DD')); console.log('New Date after subtracting one month:', newDate.format('YYYY-MM-DD'));
Output
Initial Date: 2024-12-21 New Date after subtracting one month: 2024-11-21
Using the add() Method
In this approach, we use add() method but we add a negative value instead of a positive value. The add() method in Moment.js can be used to add or subtract time. This method also supports negative values. We provide a negative number, then this method subtracts the specified duration instead of adding it.
Example
// Import Moment.js const moment = require('moment'); // Define the initial date const initialDate = moment('2024-12-21'); // Input date in YYYY-MM-DD format // Subtract one month using add() with a negative value const newDate = initialDate.add(-1, 'month'); // Display the result console.log('Initial Date:', initialDate.format('YYYY-MM-DD')); console.log('New Date after subtracting one month:', newDate.format('YYYY-MM-DD'));
Output
Initial Date: 2024-12-21 New Date after subtracting one month: 2024-11-21