Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last X days date with Moment.js

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?

like image 701
Utkarsh Bhatt Avatar asked Dec 17 '22 22:12

Utkarsh Bhatt


2 Answers

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>
like image 148
Satpal Avatar answered Dec 28 '22 11:12

Satpal


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

like image 33
Smokey Dawson Avatar answered Dec 28 '22 10:12

Smokey Dawson