Reputation: 15311
Before I start let me just say how much I hate the JavaScript Date()
object! I really hate it and I would usually use a library like date.js however I have to use my own JavaScript for this problem....
Okay, I wish to create an array of dates from today until a specific date or for a specific number of days... in this example I will set it for a number of specific days (like 365). I will use this array to populate a select in my application later.
I wish to capture today's date, then add an integer to it to get the next date, then the next, etc, etc... and format these dates as dd/mm/yyyy (I haven't included this part).
So here is my code and I have noticed that my loop starts to jump/miss days after the second index/loop
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth() + 1,
yyyy = today.getFullYear(),
today,
startDate,
d,
i,
dateArray = [];
if( dd < 10 ){
dd='0' + dd
}
if( mm < 10 ){
mm='0' + mm
}
startDate = yyyy +'-'+ mm +'-' + dd;
d = new Date(startDate)
for(i = 0; i < 365; i++){
d.setDate(d.getDate() + i);
// I will format 'd' to dd/mm/yyyy later
dateArray.push(d)
console.log(d);
}
My console is logging the following (I have shown the first 4 outputs to demonstrate my problem), notice how we miss Friday, then Sunday and Monday:
> Wed Apr 16 2014 02:00:00 GMT+0200 (CEST)
> Thu Apr 17 2014 02:00:00 GMT+0200 (CEST)
> Sat Apr 19 2014 02:00:00 GMT+0200 (CEST)
> Tue Apr 22 2014 02:00:00 GMT+0200 (CEST)
I am obviously going about this the wrong way can someone please advise me on how to use the Date() object correctly and where I am going wrong with my loop.
Thanks in advance
Upvotes: 0
Views: 958
Reputation: 6120
You are using the same object over and over. Take this for example:
- You start with Apr 16th
- You add 1 to Apr 16th, and it becomes Apr 17th
- Now you add 2 to the date, which at the moment is Apr 17th, so it becomes Apr 19th
- Now you add 3 to the date, which at the moment is Apr 19th, so it becomes Apr 22nd
- ...
You should see what I am talking about. Finally, you should do something like this:
d = new Date(startDate)
for(i = 0; i < 365; i++){
c = new Date().setDate(d.getDate() + i);
dateArray.push(c)
console.log(c);
}
Or as the Tom Fenech said, you can just add +1
instead of +i
to your current date object (d
).
Upvotes: 1
Reputation: 74665
Due to your loop, you're adding 1, 2, then 3 to d
. If you want them to be consecutive you change + i
to + 1
, like:
for(i = 0; i < 365; i++){
d.setDate(d.getDate() + 1);
// I will format 'd' to dd/mm/yyyy later
dateArray.push(d)
console.log(d);
}
Upvotes: 2