Question

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'm wondering if there's any simpler 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.]

Was it helpful?

Solution

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

console.log(d);

OTHER TIPS

var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);
 day.setDate(day.getDate() -1); //will be wrong

this will return wrong day. under UTC -03:00, check for

var d = new Date(2014,9,19);
d.setDate(d.getDate()-1);// will return Oct 17

Better use:

var n = day.getTime();
n -= 86400000;
day = new Date(n); //works fine for everything

getDate()-1 should do the trick

Quick example:

var day = new Date( "January 1 2008" );
day.setDate(day.getDate() -1);
alert(day);
origDate = new Date();
decrementedDate = new Date(origDate.getTime() - (86400 * 1000));

console.log(decrementedDate);

setDate(dayValue)

dayValue is 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.

Working with dates in JS can be a headache. So the simplest way is to use moment.js for any date operations.

To subtract one day:

const date = moment().subtract(1, 'day')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top