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 3 of 3
  1. #1
    New Coder
    Join Date
    Aug 2007
    Posts
    21
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Date object and date arithmetics problem

    Hello,

    I have a function that is called when the page loads:

    Code:
    function loadStuff() {
        today = new Date(); //today's date, e.g. Friday August 24, 2007
    }
    Then, I have a function that should change 'today' by one week up or down:

    Code:
    function changeWeek(direction) {
        var oneMinute = 60 * 1000; //number of milliseconds in a minute
        var oneHour = 60 * oneMinute;
        var oneDay = 24 * oneHour;
        var oneWeek = 7 * oneDay; //number of milliseconds in a week
    
        if (direction == 'up') {
            var newTodayInMS = today.getTime() + oneWeek;
        } else {
            var newTodayInMS = today.getTime() - oneWeek;
        }
    
        today.setTime(newTodayInMS);
        alert (today);
    }
    In the body of the page I have 2 buttons: one calls changeWeek('up') on click, the other calls changeWeek('down') on click.

    Calling changeWeek('up') produces: Thu Sep 06 (i.e. 2 weeks in advance)
    Calling changeWeek('down') produces: Thu Aug 23 (i.e. 1 day in the past)

    Could anyone tell me why just adding milliseconds to the current date doesn't work?

    Thanks.

  • #2
    ess
    ess is offline
    Regular Coder
    Join Date
    Oct 2006
    Location
    United Kingdom
    Posts
    866
    Thanks
    7
    Thanked 30 Times in 29 Posts
    Not sure why to say the truth, but if you are looking for another way of adding a week to a defined date in JS, why not use getDate() and setDate()

    check the following documentation from Mozilla.
    http://developer.mozilla.org/en/docs...ts:Date_Object

    cheers,
    Ess

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    I don't see your problem - your script works fine for me.


  •  

    Posting Permissions

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