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.]
JavaScript Arithmetic (Math) Decrementing (--)The decrement operator ( -- ) decrements numbers by one. If used as a postfix to n , the operator returns the current n and then assigns the decremented the value. If used as a prefix to n , the operator assigns the decremented n and then returns the changed value.
To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.
const date = new Date(); date. setDate(date. getDate() + 1); // ✅ 1 Day added console.
To increment a JavaScript date object by one or more days, you can use the combination of setDate() and getDate() methods that are available for any JavaScript Date object instance. The setDate() method allows you to change the date of the date object by passing an integer representing the day of the month.
var d = new Date(); d.setDate(d.getDate() - 1); console.log(d);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With