beaumondo beaumondo - 1 year ago 684
Javascript Question

Format date and Subtract days using Moment.js

I would like a variable to hold yesterdays date in the following format DD-MM-YYYY using Moment.js. So if today is 15-04-2015 I would like to subtract a day and have 14-4-2015.

Ive tried a few combinations like:

startdate = moment().format('DD-MM-YYYY');
startdate.subtract(1, 'd');

And that

startdate = moment().format('DD-MM-YYYY').subtract(1, 'd');

and also that

startdate = moment();
startdate.subtract(1, 'd');

But not getting it...

Answer Source

You have multiple oddities happening. The first has been edited in your post, but it had to do with the order that the methods were being called.

.format returns a string. String does not have a subtract method.

The second issue is that you are subtracting the day, but not actually saving that as a variable.

Your code, then, should look like:

var startdate = moment();
startdate = startdate.subtract(1, "days");
startdate = startdate.format("DD-MM-YYYY");

However, you can chain this together; this would look like:

var startdate = moment().subtract(1, "days").format("DD-MM-YYYY");

The difference is that we're setting startdate to the changes that you're doing on startdate, because moment is non-destructive.