Get last 7 days' dates as an array from today's date using momentJs, ReactJs

Viewed 2888

with reference to my last quetsion how to get previous dates from given date

let n=8
        while(n>0){
            console.log(n)
            resultDates.push(moment().subtract(1,"day"))
            n--;
            
        }
       
        console.log(resultDates);

3 Answers

const current = moment()
        let n=8
        while(n>0){
            console.log(n)
            resultDates.push(current.format("YYYY-MM-DD"))
            current.subtract(1,"day")
            n--;
            
        }

Modern ecmascript approach

const today = moment();
const res = Array(7).fill().map(
  () => today.subtract(1, 'd').format('YYYY-MM-DD')
);

Just FYI that moment has an official plugin (it is in their documentation) in regards to ranges which makes what you are trying to achieve easy via (nodejs for example):

const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);

const range = moment.range(moment().subtract(8,"day"), moment());

console.log(Array.from(range.by('day')))

That would give you an output like:

[ moment("2018-10-16T17:08:21.560"),
  moment("2018-10-17T17:08:21.560"),
  moment("2018-10-18T17:08:21.560"),
  moment("2018-10-19T17:08:21.560"),
  moment("2018-10-20T17:08:21.560"),
  moment("2018-10-21T17:08:21.560"),
  moment("2018-10-22T17:08:21.560"),
  moment("2018-10-23T17:08:21.560"),
  moment("2018-10-24T17:08:21.560") ]
Related