Reputation: 11642
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.
Upvotes: 79
Views: 116470
Reputation: 166
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
Upvotes: 7
Reputation: 3816
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/
Upvotes: 2
Reputation: 473
for a date picker y use
first_day: moment()
.subtract(5, "day")
.endOf("day")
.toDate(),
last_day: moment()
.endOf("day")
.toDate(),
Upvotes: 2
Reputation: 4076
Easiest method to get last 7th day
moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss')
Upvotes: 0
Reputation: 1756
May be:
dateTo = moment().format('YYYY-MM-DD');
dateFrom = moment().subtract(7,'d').format('YYYY-MM-DD');
Upvotes: 174
Reputation: 9958
The date object, when casted, is in milliseconds. so:
dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('YYYY-MM-DD');
Upvotes: 6