Get All 90 Days Before Today with Javascript

I want to have all 90 days before today as an array. I couldn't any solution in StackOverflow or Google.

const now = new Date(); 
const daysBefore = now.setDate(priorDate.getDate() - 90);

My expected result is an array of 90 days before today:

const days = [
 '2021-06-03T05:45:36.685Z',
 '2021-06-02T05:45:36.685Z',
 '2021-06-01T05:45:36.685Z',
 '2021-05-30T05:45:36.685Z',
 ...
]
3

1 Answer

Create an array of dates by creating a new array of length 90 and mapping each entry to a new date that is now minus the index number of days

const now = new Date()
const length = 90

const days = Array.from({ length }, (_, days) => {
  let day = new Date(now) // clone "now"
  day.setDate(now.getDate() - days) // change the date
  return day
})

console.log(days)

This creates an array of Date instances starting with now and working back for 90 days (descending order).

See also Array.from()

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest