0

Hey i want to get the last 14 days in JavaScript. I tried following code:

var ourDate = new Date();
for (let index = 0; index < 14; index++) {
    var pastDate = ourDate.getDate() - index;
    ourDate.setDate(pastDate);
    console.log(ourDate.toDateString(), " - ", index);
}

but the console output is following:

Sat Jan 23 2021  -  0
Fri Jan 22 2021  -  1
Wed Jan 20 2021  -  2
Sun Jan 17 2021  -  3
Wed Jan 13 2021  -  4
Fri Jan 08 2021  -  5
Sat Jan 02 2021  -  6
Sat Dec 26 2020  -  7
Fri Dec 18 2020  -  8
Wed Dec 09 2020  -  9
Sun Nov 29 2020  -  10
Wed Nov 18 2020  -  11
Fri Nov 06 2020  -  12
Sat Oct 24 2020  -  13

Which does not make sense. Could someone help me with this? I used this code: LINK TO TUTORIAL

  • 1
    Why does it not make sense? You're subtracting 1 day, then 2 days, then 3 days, then 4 days... – Niet the Dark Absol Jan 23 '21 at 18:17
  • Assuming it was 23 January when you did the test, then the first time through the loop you subtract 0 so the date is still the 23 January and that is what is logged to the console, along with a hyphen and 0. The next time it goes down by 1 and so on. I don't think you have a problem. – A Haworth Jan 23 '21 at 18:25

2 Answers2

0

I just solved it myself. I never retested the ourDate so it first removed 0 than 1 than 2 but never reseted. Just have to create the ourDate in the for loop:

for (let index = 0; index < 14; index++) {
    var ourDate = new Date();
    var pastDate = ourDate.getDate() - index;
    ourDate.setDate(pastDate);
    console.log(ourDate.toDateString(), " - ", index);
}
0

You can try this snippet:

const now = new Date();
const days = Array.from({ length: 14 }, (_, x) => new Date(now - 1000 * 60 * 60 * 24 * x));
for (let day of days) console.log(day.toDateString());

Or a more general solution:

const msInDay = 1000 * 60 * 60 * 24;
const daysAgo = (date, count) => new Date(date - msInDay * count);
const lastDays = (date, count) => Array.from({ length: count }, (_, x) => daysAgo(date, x));

const last14days = lastDays(new Date(), 14);
for (let day of last14days) console.log(day.toDateString());
shadeglare
  • 7,006
  • 7
  • 47
  • 59
  • Adding days by adding 24 hours is not a good idea where daylight saving is observed because not all days are 24 hours long. See [*How can I add 1 day to current date?*](https://stackoverflow.com/questions/9989382/how-can-i-add-1-day-to-current-date/9989458#9989458) – RobG Jan 24 '21 at 01:27