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

JavascriptDateMomentjsSubstr

Javascript Problem Overview


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:

    dateTo = moment(new Date()).format('YYYY-MM-DD');
    dateFrom = moment(new Date() - 7).format('YYYY-MM-DD');

   console.log(dateFrom);
   console.log(dateTo);

But all returned values are same.

Javascript Solutions


Solution 1 - Javascript

May be:

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

moment#subtract

Solution 2 - Javascript

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

dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('YYYY-MM-DD'); 

Solution 3 - Javascript

You can use:

moment().subtract(1,'w')

to subtract one week (7 days) from the current date.

NOTE:
1. w for week
2. d for days
3. m for month
4. y for year

Solution 4 - Javascript

for a date picker y use

 first_day: moment()
    .subtract(5, "day")
    .endOf("day")
    .toDate(),
  last_day: moment()
    .endOf("day")
    .toDate(),

Solution 5 - Javascript

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/

Solution 6 - Javascript

Easiest method to get last 7th day

moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionredromView Question on Stackoverflow
Solution 1 - Javascriptstu_shaView Answer on Stackoverflow
Solution 2 - JavascriptVinz243View Answer on Stackoverflow
Solution 3 - JavascriptSamuel ChibuikeView Answer on Stackoverflow
Solution 4 - JavascriptIoan BeilicView Answer on Stackoverflow
Solution 5 - JavascriptRafique MohammedView Answer on Stackoverflow
Solution 6 - JavascriptRohit ParteView Answer on Stackoverflow