Reputation: 680
I am trying to get date from day of the month in a loop. The code works for the first few days, and from then on it is returning random dates.
Any help here?
var now = new Date();
var initDate = new Date(now.getYear() + 1900, 0);
for (var i = 1 ; i <366 ; i++) {
var day = dateFromDay(i, initDate);
document.write(" Day " + i + " : " + day);
document.write("<br>");
}
function dateFromDay(day, initDate) {
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var cur = new Date(initDate.setDate(day));
cur = months[cur.getMonth()] + " " + cur.getDate();
return cur;
}
Output:
...
...
Day 29 : Jan 29
Day 30 : Jan 30
Day 31 : Jan 31
Day 32 : Feb 1
// From here the output gets messed up
Day 33 : Mar 4
Day 34 : Apr 3
Day 35 : May 5
Day 36 : Jun 5
Day 37 : Jul 7
Day 38 : Aug 7
Day 39 : Sep 8
Day 40 : Oct 10
Day 41 : Nov 10
Day 42 : Dec 12
Day 43 : Jan 12
Day 44 : Feb 13
...
...
Upvotes: 2
Views: 327
Reputation: 413712
Calling setDate()
on your "initDate" variable updates that date. Thus, as soon as you overflow January into February, the next call will immediately spill into the next month.
You don't need the "initDate" variable. Start with a freshly-constructed date on each call to the function for the current year, month of January (0), and whatever day number you want. The resulting Date instance will be your date.
Thus:
function dayNumberToDate( dayNumber ) {
var thisYear = new Date().getFullYear(); // no need to add 1900
return new Date(thisYear, 0, dayNumber);
}
alert(dayNumberFromDate( 271 )); // alerts Thu Sep 27 2012 00:00:00 GMT-0500 (CDT) (for me)
Upvotes: 1
Reputation: 15644
Move the code given below inside your for loop before this line var day = dateFromDay(i, initDate);
var now = new Date();
var initDate = new Date(now.getYear() + 1900, 0);
Upvotes: 0
Reputation: 50563
Change your following line:
var cur = new Date(initDate.setDate(day));
for this one:
var cur = new Date();
cur.setDate( initDate.getDate()+day );
Upvotes: 0