[ACCEPTED]-What's the simplest way to decrement a date in Javascript by 1 day?-date
Accepted answer
var d = new Date();
d.setDate(d.getDate() - 1);
console.log(d);
0
var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);
0
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
getDate()-1
should do the trick
Quick example:
var day = new Date( "January 1 2008" );
day.setDate(day.getDate() -1);
alert(day);
0
origDate = new Date();
decrementedDate = new Date(origDate.getTime() - (86400 * 1000));
console.log(decrementedDate);
0
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.
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')
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.