JS getting dynamic dates for a range

Viewed 206

I have a small snippet of JS code that I've been using to set dates on the header of an HTML table based on an object, like so:

dates() {
  const dates = [...new Set(this.rows.map(r => r.pri_date))]
  return dates.sort((a,b) => new Date(a) - new Date(b))
},

in this example, rows was just a json object

What I actually need is to set a table header of dates regardless of the dates in the object. I need the first column to be today's date, and then the following 7 days.

So right now it would look like:

2021-11-02 | 2021-11-03 | 2021-11-04 | 2021-11-05 |2021-11-06 | 2021-11-07 | 2021-11-08 | 2021-11-09

How can I change the above code to be a dynamic date range based on the current day's date (trying to keep the format and return the same in my code)

1 Answers

Try this:

const today = Date.now();
const dates = [
  ...this.rows.map((x,i) => {
    return new Date(today + 86400000 * i).toISOString().substring(0,10);
    // 86400000 ms is 24hours
  })
]
Related