76

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

But all returned values are same.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
redrom
  • 11,502
  • 31
  • 157
  • 264

6 Answers6

169

May be:

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

moment#subtract

str
  • 42,689
  • 17
  • 109
  • 127
stu_sha
  • 1,706
  • 1
  • 10
  • 2
6

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

dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('YYYY-MM-DD'); 
Vinz243
  • 9,654
  • 10
  • 42
  • 86
5

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
Samuel Chibuike
  • 146
  • 2
  • 4
2

for a date picker y use

 first_day: moment()
    .subtract(5, "day")
    .endOf("day")
    .toDate(),
  last_day: moment()
    .endOf("day")
    .toDate(),
Ioan Beilic
  • 463
  • 7
  • 12
2

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/

Rafique Mohammed
  • 3,666
  • 2
  • 38
  • 43
0

Easiest method to get last 7th day

moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss')
Rohit Parte
  • 3,365
  • 26
  • 26