Friday, February 4, 2011

What's the simplest way to decremement a date in Javascript by 1 day?

I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.

It always seems to take more code than necessary when I do this, so I wonder if there's a simple way.

What's the simplest way of doing this?

[Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]

  • var today = new Date();
    var yesterday = new Date().setDate(today.getDate() -1);
    
  • var d = new Date();
    d.setDate(d.getDate()-1);
    
    From Marius
  • getDate()-1 should do the trick

    Quick example:

    var day = new Date( "January 1 2008" );
    day.setDate(day.getDate() -1);
    alert(day);
    
    From Phil
  • Thanks @Marius, @liammclennan and @Phil - I did not know setDate() also rolled months and years back automatically.

    I accepted @Marius as first answer for being so quick. ;o)

  • setDate(dayValue)

    dayValue = An integer from 1 to 31, representing the day of the month.

    from https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate

    The behaviour solving your problem (and mine) seems to be out of specification range.

    What seems to be needed are addDate(), addMonth(), addYear() ... functions.

0 comments:

Post a Comment