Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Feb 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Javascript Date Problems

    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.

    Code:
    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
    Last edited by ourvalley.ca; 06-19-2009 at 11:33 PM.

  • #2
    Regular Coder
    Join Date
    Mar 2006
    Posts
    725
    Thanks
    35
    Thanked 132 Times in 123 Posts
    Code:
    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>'))
    Last edited by mrhoo; 06-19-2009 at 03:54 PM.

  • #3
    New to the CF scene
    Join Date
    Feb 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you so much mrhoo, that works wonderfully!!

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

  • #4
    Regular Coder
    Join Date
    Mar 2006
    Posts
    725
    Thanks
    35
    Thanked 132 Times in 123 Posts
    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.
    Last edited by mrhoo; 06-19-2009 at 05:11 PM.

  • #5
    New to the CF scene
    Join Date
    Feb 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you again, and thanks for taking the time to explain my error, it makes sense to me now.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •