Open In App

How to Subtract 7 Days from Current Date with MomentJS?

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The article is all about how can we get the 7 days subtracted date from the given date. for eg: if the given date is 28-08-2024 then it should print 21-08-2024, that is the exactly subtraction of the seven day from the given day.

These are the following approaches:

Using the subtract() Method

In Moment, the subtract() method. Of all the ways we have seen to subtract days off a date, the js is the simplest. The days to be subtracted can be mentioned along with the unit of time that is, days, months or years.

Example: This example shows the use of substract() method.

JavaScript
const moment = require("moment");
const date = moment().subtract(7, "days");
console.log(date.format("YYYY-MM-DD"));

Output:

2024-08-21

Using the add() Method with a Negative Value

Another way to subtract days is to use the add() method with a negative value. This approach is less common but still effective.

Syntax:

moment().add(amount, unit);

Example: This example shows the use of add() method.

JavaScript
const moment = require("moment");
const date = moment().add(-7, "days");
console.log(date.format("YYYY-MM-DD"));

Output:

2024-08-21

Conclusion

Moment. The js presents several ways through which one can transform dates and it’s very easy to remove some days from a given date. No matter by using the subtract() method, the add() method with a negative parameter or cascaded operations, Moment. js has a rather effective approach as regards the treatment of date. These issues have been described in this article and the following sections are dedicated to different ways of how the current date can be subtracted by 7 days along with an example of output of each way.


Next Article

Similar Reads