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 \'Ye
var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);
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.
var d = new Date();
d.setDate(d.getDate() - 1);
console.log(d);
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
origDate = new Date();
decrementedDate = new Date(origDate.getTime() - (86400 * 1000));
console.log(decrementedDate);
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')