[ACCEPTED]-What's the simplest way to decrement a date in Javascript by 1 day?-date

Accepted answer
Score: 33

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

console.log(d);

0

Score: 5
var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);

0

Score: 5
 day.setDate(day.getDate() -1); //will be wrong

this will return wrong day. under UTC -03:00, check 1 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
Score: 4

getDate()-1 should do the trick

Quick example:

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

0

Score: 4
origDate = new Date();
decrementedDate = new Date(origDate.getTime() - (86400 * 1000));

console.log(decrementedDate);

0

Score: 1

setDate(dayValue)

dayValue is an integer from 1 to 31, representing 4 the day of the month.

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

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

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

Score: 1

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

To subtract one day:

const date = moment().subtract(1, 'day')

More Related questions