Incrementing a date in JavaScript

Santanu picture Santanu · Sep 9, 2010 · Viewed 524.7k times · Source

I need to increment a date value by one day in JavaScript.

For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript variable.

How can I increment a date by a day?

Answer

T.J. Crowder picture T.J. Crowder · Sep 9, 2010

Three options for you:

1. Using just JavaScript's Date object (no libraries):

My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Human pointed out that it would fail with November 7, 2010 in the Eastern timezone). Instead, Jigar's answer is the correct way to do this without a library:

var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:

var lastDayOf2015 = new Date(2015, 11, 31);
snippet.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
snippet.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
snippet.log("Resulting date: " + nextDay.toISOString());
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

(This answer is currently accepted, so I can't delete it. Before it was accepted I suggested to the OP they accept Jigar's, but perhaps they accepted this one for items #2 or #3 on the list.)

2. Using MomentJS:

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)

3. Using DateJS, but it hasn't been updated in a long time:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();