Categories
JavaScript Answers

How to Format Date and Subtract Days Using Moment.js?

Spread the love

Sometimes, we want to format dates and subtract the days with moment.js.

In this article, we’ll look at how to subtract days from a date and format the result with moment.js.

Use the subtract and format Methods

We can use the moment.js’ subtract method to subtract days.

And then we can use the format method to format the resulting date.

For instance, we can write:

const startdate = moment('2020-01-01');  
const result = startdate  
  .subtract(1, "days")  
  .format("DD-MM-YYYY");  
console.log(result)

We defined the startdate variable and assign the moment object with the date we want to subtract to it.

Then we call subtract to subtract 1 day from startdate by calling it with 1 and 'days' .

And then we call format to format the date with a formatting string.

Therefore, result is '31–12–2019' .

Conclusion

We can call moment.js’ subtract method to subtract a day from a date.

And then we can call format to format the date into the format we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *