-1

I have a date array as below:

const d = ["2020-06-29T00:00:00.000Z","2020-07-06T00:00:00.000Z","2020-07-13T00:00:00.000Z","2020-07-20T00:00:00.000Z","2020-07-27T00:00:00.000Z"];

I want to shift every element in the date array into two weeks earlier from the date using forEach below from the method I found here how do I subtract one week from this date in jquery?

d.forEach(d.setDate(d.getdate() - 14));

However, I receive error while what I want is all date has shifted into two weeks earlier as below:

const d = ["2020-06-15T00:00:00.000Z","2020-06-22T00:00:00.000Z","2020-06-29T00:00:00.000Z","2020-07-13T00:00:00.000Z","2020-07-20T00:00:00.000Z"];
rain123
  • 243
  • 4
  • 13

2 Answers2

1

You can do this as below (Converting string to date and using .map()):

const d = ["2020-06-29T00:00:00.000Z","2020-07-06T00:00:00.000Z","2020-07-13T00:00:00.000Z","2020-07-20T00:00:00.000Z","2020-07-27T00:00:00.000Z"]
, result = d.map(curr => {
  const dt = new Date(curr)
  dt.setDate(dt.getDate() - 14)
  return dt.toISOString()
})

console.log(result);
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
0

Using forEach loop you can achieve this

const d = ["2020-06-29T00:00:00.000Z","2020-07-06T00:00:00.000Z","2020-07-13T00:00:00.000Z","2020-07-20T00:00:00.000Z","2020-07-27T00:00:00.000Z"];


var res = [];
d.forEach(obj => {
   var tempDate = new Date(obj);
   tempDate.setDate(tempDate.getDate() -14);
   res.push(tempDate.toISOString());
});

console.log(res);
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26