views:

368

answers:

5

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.]

+6  A: 
var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);
liammclennan
+11  A: 
var d = new Date();
d.setDate(d.getDate()-1);
Marius
+4  A: 

getDate()-1 should do the trick

Quick example:

var day = new Date( "January 1 2008" );
day.setDate(day.getDate() -1);
alert(day);
Phil
A: 

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)

ChrisThomas123
A: 

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.

John Griffiths