...

View Full Version : Resolved Javascript Date Problems



ourvalley.ca
06-19-2009, 03:27 PM
Hi Everyone,

I'm having some issues with adding dates. Here is a trimmed down version of what I'm trying to do and the output it produces.


var now = new Date();
var d = new Date()
var dt = d.getDate();
d.setDate(dt-1)

for (i = 0; i < 16; i++)
{
d.setDate(dt+i);
var cur_month = d.getMonth();
cur_month++;
document.write (d.getFullYear() + "-" + cur_month + "-" + d.getDate() + "<br>");
}

Output:
2009-6-19
2009-6-20
2009-6-21
2009-6-22
2009-6-23
2009-6-24
2009-6-25
2009-6-26
2009-6-27
2009-6-28
2009-6-29
2009-6-30
2009-7-1
2009-8-1
2009-9-2
2009-10-4

I don't understand why all of a sudden it starts adding months instead of days.

Any help would be great.

Thanks
Sandy

mrhoo
06-19-2009, 03:47 PM
var i=0, A=[], d = new Date();
d.setDate(d.getDate()-1);
while (i++ < 16){
d.setDate(d.getDate()+1);
A[A.length]=d.getFullYear() + "-" + (d.getMonth()+1) + "-" + d.getDate() ;

}
alert(A.join('\n'))
// document.write(A.join('<br>'))

ourvalley.ca
06-19-2009, 04:09 PM
Thank you so much mrhoo, that works wonderfully!!

Are you able to explain why the way I had it didn't work?

mrhoo
06-19-2009, 05:05 PM
d.setDate changes d to the new date.

the asignment after July 1 adds i (13) days to dt (19) which makes the 32nd day of July, which is actually August 1-
then 14+19 makes August 33, or Sept 2, and 15+19 sets the date to Sept 34, or Oct 4.

ourvalley.ca
06-19-2009, 11:32 PM
Thank you again, and thanks for taking the time to explain my error, it makes sense to me now.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum