Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.]

like image 490
ChrisThomas123 Avatar asked Aug 28 '08 09:08

ChrisThomas123


People also ask

How do you decrement in JavaScript?

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.

How do you subtract days in JavaScript?

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.

How can I add 1 day to current date?

const date = new Date(); date. setDate(date. getDate() + 1); // ✅ 1 Day added console.

How can I increment a date by one day in JavaScript?

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.


1 Answers

var d = new Date();  d.setDate(d.getDate() - 1);    console.log(d);
like image 108
Marius Avatar answered Sep 20 '22 21:09

Marius