Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

javascript - get last 14 Dates

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

question from:https://stackoverflow.com/questions/65862734/get-last-14-dates

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...