Format date and Subtract days using Moment.js

后端 未结 7 838
别那么骄傲
别那么骄傲 2020-11-29 20:28

I would like a variable to hold yesterday\'s date in the format DD-MM-YYYY using Moment.js. So if today is 15-04-2015, I would like to subtract a day and have 1

相关标签:
7条回答
  • 2020-11-29 21:33

    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 destructive.

    0 讨论(0)
提交回复
热议问题