I want to get the last x
dates from the current date using Moment.js
.
const moment = require('moment');
let dates;
const dates = [];
const NUM_OF_DAYS = 12; // get last 12 dates.
for (let i = 0; i < NUM_OF_DAYS; i++) {
date = moment();
date.subtract(1, 'day').format('DD-MM-YYYY');
dates.push(date);
}
console.log(dates);
The result of this code is as follows:
[ moment("2018-07-09T11:40:04.663"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675"),
moment("2018-07-09T11:40:04.675") ]
This is the same date and not the previous of what I want for each iteration.
I know the issue is with the line date = moment()
because it is returning the current timestamp and not the previous at each step.
How can I fix this?
You are pushing same variable to array and always subtracting 1 from current moment.
Declare date
variable inside the loop and subtract i
for(...){
let date = moment();
date.subtract(i, 'day')
...
}
const dates = [];
const NUM_OF_DAYS = 12; // get last 12 dates.
for (let i = 0; i < NUM_OF_DAYS; i++) {
let date = moment();
date.subtract(i, 'day').format('DD-MM-YYYY');
dates.push(date);
}
console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Try this
const moment = require('moment');
let dates;
const dates = [];
const NUM_OF_DAYS = 12; // get last 12 dates.
for (let i = 0; i < NUM_OF_DAYS; i++) {
let date = moment();
date.subtract(i, 'day').format('DD-MM-YYYY');
dates.push(date);
}
console.log(dates);
In your code you were looping through and only subtracting 1 each time and not actually updating the number each time which is why you were only getting the same date, I've updated your code so as it loops it will update the number of days
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With