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
Updated on: 2024-12-23T11:04:35+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements