Format date and Subtract days using Moment.js

后端 未结 7 839
别那么骄傲
别那么骄傲 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:06

    I think you have got it in that last attempt, you just need to grab the string.. in Chrome's console..

    startdate = moment();
    startdate.subtract(1, 'd');
    startdate.format('DD-MM-YYYY');
    "14-04-2015"
    
    startdate = moment();
    startdate.subtract(1, 'd');
    myString = startdate.format('DD-MM-YYYY');
    "14-04-2015"
    myString
    "14-04-2015"
    
    0 讨论(0)
  • 2020-11-29 21:07
    startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');
    
    0 讨论(0)
  • 2020-11-29 21:08
    var date = new Date();
    
    var targetDate = moment(date).subtract(1, 'day').toDate(); // date object
    

    Now, you can format how you wanna see this date or you can compare this date with another etc.

    toDate() function is the point.

    0 讨论(0)
  • 2020-11-29 21:18

    In angularjs moment="^1.3.0"

    moment('15-01-1979', 'DD-MM-YYYY').subtract(1,'days').format(); //14-01-1979
    or
    moment('15-01-1979', 'DD-MM-YYYY').add(1,'days').format(); //16-01-1979
    ``
    
    
    
    
    0 讨论(0)
  • 2020-11-29 21:21

    Try this:

    var duration = moment.duration({'days' : 1});
    moment().subtract(duration).format('DD-MM-YYYY');
    

    This will give you 14-04-2015 - today is 15-04-2015

    Alternatively if your momentjs version is less than 2.8.0, you can use:

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

    Instead of this:

    startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');
    
    0 讨论(0)
  • 2020-11-29 21:23

    startdate = moment().subtract(1, 'days').startOf('day')

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