Moment JS - how to subtract 7 days from current date?

后端 未结 5 1270
醉话见心
醉话见心 2020-12-08 06:03

I would like to subtract 7 days from current date to get formatted date YYYY-MM-DD using moment.js library.

I tried to do by this way:



        
相关标签:
5条回答
  • 2020-12-08 06:45

    The date object, when casted, is in milliseconds. so:

    dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('YYYY-MM-DD'); 
    
    0 讨论(0)
  • 2020-12-08 06:49

    May be:

    dateTo = moment().format('YYYY-MM-DD');
    dateFrom = moment().subtract(7,'d').format('YYYY-MM-DD');
    

    moment#subtract

    0 讨论(0)
  • 2020-12-08 06:53

    for a date picker y use

     first_day: moment()
        .subtract(5, "day")
        .endOf("day")
        .toDate(),
      last_day: moment()
        .endOf("day")
        .toDate(),
    
    0 讨论(0)
  • 2020-12-08 06:55

    Easiest method to get last 7th day

    moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss')
    
    0 讨论(0)
  • 2020-12-08 06:59

    The question is outdated so does the solution.

    Using Moment v2.29 +

    You can add or subtract days using following ways

    moment().day(-7); // last Sunday (0 - 7)
    moment().day(0); // this Sunday (0)
    moment().day(7); // next Sunday (0 + 7)
    moment().day(10); // next Wednesday (3 + 7)
    moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
    

    For more please refer the official documentation https://momentjs.com/docs/#/get-set/

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