554

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?

jmj
  • 237,923
  • 42
  • 401
  • 438
Santanu
  • 7,764
  • 7
  • 26
  • 24
  • 1
    Does this answer your question? [Add days to JavaScript Date](https://stackoverflow.com/questions/563406/add-days-to-javascript-date) – Michael Freidgeim Jun 03 '20 at 06:10

20 Answers20

968

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:

// To do it in local time
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

// To do it in UTC
var tomorrow = new Date();
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);

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

// (local time)
var lastDayOf2015 = new Date(2015, 11, 31);
console.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
console.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
console.log("Resulting date: " + nextDay.toISOString());

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();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • But I have date 2010-09-11 in a variable by using document.getElementById("arrival_date").value,it shows invalid date – Santanu Sep 09 '10 at 07:37
  • 1
    @santanu: That's a completely different problem: Date parsing (getting a date by interpreting a string). If that format is static, you can parse it yourself and feed the results into the `Date` constructor (`new Date(year, month, date)`); see section 15.9.2.1 of the [specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm); if you want to accept a range of formats, definitely take a look at [DateJS](http://www.datejs.com). – T.J. Crowder Sep 09 '10 at 08:12
  • 1
    @santanu: Just to follow-on the above: Some browsers may successfully parse that format with `Date.parse` (which returns a number of milliseconds you can then feed into `new Date(ms)`). But beware, that can vary from browser to browser. Until recently, implementations could do just about anything they wanted to in `Date.parse`. The new 5th edition specification now has a minimum format that must be accepted, but I wouldn't count on that yet. – T.J. Crowder Sep 09 '10 at 08:18
  • 1
    I just wanted to add a second to a Date instance; this worked for me `x = new Date(); x2 = new Date(x.getTime() + 1000)`, where 1000 is a millisecond increment. – berto Dec 05 '14 at 19:42
  • Make sure the days, which could (and quite likely is) be a variable is an `int` and not a string. Doing `tomorrow.setDate(tomorrow.getDate() + days);` where `days` is user input will append the string to the end of the date instead of simply adding a day, so you'll need to `parseInt` like so: `tomorrow.setDate(tomorrow.getDate() + parseInt(days));` – Mike May 08 '15 at 13:22
  • @PratikBhalodiya: Quoting the answer above: *"This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover"*. – T.J. Crowder Sep 19 '16 at 14:27
  • Something's wrong with 1st solution. Try this: var unavailableDates = []; for (var d = new Date('2017-05-11'); d < new Date('2017-05-13'); d.setDate(d.getDate() + 1)) { console.log(d); unavailableDates.push(d); } console.log(unavailableDates); In console log, unavailableDates will contain [Sat May 13 2017 07:00:00 GMT+0700 (+07), Sat May 13 2017 07:00:00 GMT+0700 (+07)] I mean they are all 2017-05-13 – 0xh8h May 12 '17 at 05:36
  • 1
    @piavgh: There's nothing wrong with the first solution, it's just how you're using it. `Date` objects are mutable. You're storing the **same** `Date` object three times in the array. If you want three different `Date` objects, you have to create three objects: `var unavailableDates = []; for (var d = new Date('2017-05-11'); d < new Date('2017-05-13'); d.setDate(d.getDate() + 1)) { unavailableDates.push(new Date(+d)); }` – T.J. Crowder May 12 '17 at 06:54
  • Solution 1 seems to fail sometimes. Try using Jun 30 2018 as the initial date and then adding 1. You end up with Jul 31 2018. – stackedAE Jul 05 '18 at 07:33
  • @stackedAE - [Works for me](http://jsfiddle.net/f3a9o1w6/). I'm guessing you started with July 30th, not June 30th, because of the whole 0 = January thing. When saying something like this doesn't work, a demo of what you did (or at least the code) really helps. – T.J. Crowder Jul 05 '18 at 07:43
  • The problem seems to occur when you make a new Date object and set the date from another Date object as in your original answer. See here: http://jsfiddle.net/f3a9o1w6/5/ For some reason it seems if you call setDate() on the same Date it does work, but it doesn't work if you setDate() on a new Date. – stackedAE Jul 06 '18 at 03:41
  • @stackedAE - That **isn't** what the code in the answer does. You're taking a date object currently set to someone in July (`new Date()`) and changing its day-of-month (only) to 31 (`.setDate(...)`). So naturally you get July 31st. If you did what's in the answer so the date is the same as the first date (the month is June), it's fine: http://jsfiddle.net/zLwv7bru/ – T.J. Crowder Jul 06 '18 at 06:22
  • @stackedAE - That said, `new Date(someOtherDate)` isn't a foolproof way to copy dates and I shouldn't have used it (fixed above). It goes through the string constructor. Instead, should go through the number constructor: `new Date(+someOtherDate)`: http://jsfiddle.net/93uo7e4c/ – T.J. Crowder Jul 06 '18 at 06:22
  • if you use moment, you can use `today` for tomorrow, you can simply use `clone()`, like this: `var tomorrow = today.clone().add(1, 'days');`, it does create a new instance, but its easier to understand. – Art3mix Aug 31 '20 at 16:54
  • Does not work for 2016-03-13: `d = new Date("2016-03-13T00:00:00.000Z"), d.setDate(d.getDate()+1), d.toISOString()` – Azmisov Aug 04 '21 at 23:37
  • I get `"2016-03-13T23:00:00.000Z"` in latest Chrome, Firefox, and NodeJS. I'm guessing your local timezone doesn't use DST, so it appears to work for you, while other people it may not. – Azmisov Aug 06 '21 at 00:13
  • @Azmisov - We use DST too, but on different dates to yours. I see what's going on now (and should have earlier). The code is adding one day in **local time** (`setDate`/`getDate` are local time), but because you're looking at the result in UTC instead of local time, it seems wrong. I can replicate your result using U.S. Pacific time (but any timezone west of GMT that changes DST on that date should work). `2016-03-13T00:00:00.000Z` is March 12th at 16:00 PST. Add a day and you get March 13th at 16:00 PDT (note DST kicked in), which is March 13 23:00 GMT. *(cont'd)* – T.J. Crowder Aug 06 '21 at 08:31
  • 1
    *(continuing)* The problem is looking at changes to local time in UTC. Local should be viewed as local and changed as local; UTC should be viewed as UTC and changed as UTC. So this works in local time (I've used 16:00 for Pacific but change it to match your timezone, though the hour doesn't matter): `d = new Date(2016, 3 - 1, 13, 16), d.setDate(d.getDate()+1), d.toString()` And this works in UTC (via `getUTCDate`/`setUTCDate`): `d = new Date("2016-03-13T00:00:00.000Z"), d.setUTCDate(d.getUTCDate()+1), d.toISOString()`. Thanks for pointing that out! I've updated the answer to mention it. – T.J. Crowder Aug 06 '21 at 08:31
  • 1
    @T.J.Crowder Okay cool, thanks for looking into it. I hadn't looked at the get/setUTCDate functions before – Azmisov Aug 07 '21 at 16:30
  • @Azmisov - I really appreciate your bringing it up. Happy coding! :-) – T.J. Crowder Aug 07 '21 at 16:35
196
var myDate = new Date();

//add a day to the date
myDate.setDate(myDate.getDate() + 1);
jmj
  • 237,923
  • 42
  • 401
  • 438
  • But I have date 2010-09-11 in a variable by using document.getElementById("arrival_date").value,it shows invalid date – Santanu Sep 09 '10 at 07:35
  • 1
    @sanatu: In that case you need to format the string in a way that the browser will accept. Chrome accepts `new Date("2009-09-11")` but Firefox doesn't. I think most browsers accept `new Date("2009/09/11")` so an easy solution would be `var arrivalDate = document.getElementById('arival_date').value; var dayAfter = new Date(arrival_date.replace(/-/g, '/')); dayAfter.setDate(dayAfter.getDate()+1);`. – David Hedlund Sep 09 '10 at 07:43
  • 6
    A more solid approach than replacing `-` with `/` and hoping that browsers will accept it, would be to divide the string into parts: `var dateParts = arrivalDate.split('-'); var y = parseInt(dateParts[0], 10); var m = parseInt(dateParts[1], 10); var d = parseInt(dateParts[2], 10); var dayAfter = new Date(y, m-1, d+1);` Note that we're using `m-1` here, because javascript months are enum values (January being 0, not 1), and `d+1` because we're doing the incrementation already in the initial assignment (it'll automatically correct for Feb 29th, etc.) – David Hedlund Sep 09 '10 at 07:50
  • Does not work for 2016-03-13: `d = new Date("2016-03-13T00:00:00.000Z"), d.setDate(d.getDate()+1), d.toISOString()` – Azmisov Aug 04 '21 at 23:40
56

The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:

var tomorrow = new Date(today.getTime()+1000*60*60*24);
approxiblue
  • 6,982
  • 16
  • 51
  • 59
  • This is the best answer. Can increment/decrement easily as much days as requested; just by multiplying `1000*60*60*24` x `DaysToBeAdded` – Khalil Khalaf Jul 12 '17 at 16:00
  • 1
    Or, `new Date(+new Date() + 1000*60*60*24)`, but it is actually similar to `getTime()` / `setTime()`, really. – Polv Jan 07 '20 at 14:09
  • 7
    Don't do this unless your date is in UTC or another time zone that doesn't have daylight savings time. Otherwise, for 2 days per year, it will give unexpected results. – ItalyPaleAle Mar 28 '20 at 22:24
  • 2
    A one-liner: `new Date(Date.now()+1000*60*60*24);` – aiyan Apr 13 '20 at 13:01
45

Tomorrow in one line in pure JS but it's ugly !

new Date(new Date().setDate(new Date().getDate() + 1))

Here is the result :

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
jpmottin
  • 2,717
  • 28
  • 25
  • the one line was the exactly what I needed for Vue.js expression, as I had to drop a param and there's no place to do setting and getting in several lines. Thanks! – Cortex Aug 09 '20 at 07:47
  • Does not work for 2016-03-13: `d = new Date("2016-03-13T00:00:00.000Z"), d.setDate(d.getDate()+1), d.toISOString()` – Azmisov Aug 04 '21 at 23:35
  • @Azmisov Just checked again for you. `d = new Date("2016-03-13T00:00:00.000Z");` in memory I have : `Sun Mar 13 2016 01:00:00 GMT+0100 (Central European Standard Time)`. Then I do `d.setDate(d.getDate()+1)` and in memory I have `1457913600000` or in pretty print `Mon Mar 14 2016 01:00:00 GMT+0100 (Central European Standard Time)`. Finally `d.toISOString()` that gives me the day after 13 -> 14 : `"2016-03-14T00:00:00.000Z"`. So Everything works perfectly fine. – jpmottin Aug 06 '21 at 06:06
38

None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)

The below AddDays javascript function accounts for daylight saving time:

function addDays(date, amount) {
  var tzOff = date.getTimezoneOffset() * 60 * 1000,
      t = date.getTime(),
      d = new Date(),
      tzOff2;

  t += (1000 * 60 * 60 * 24) * amount;
  d.setTime(t);

  tzOff2 = d.getTimezoneOffset() * 60 * 1000;
  if (tzOff != tzOff2) {
    var diff = tzOff2 - tzOff;
    t += diff;
    d.setTime(t);
  }

  return d;
}

Here are the tests I used to test the function:

    var d = new Date(2010,10,7);
    var d2 = AddDays(d, 1);
    document.write(d.toString() + "<br />" + d2.toString());

    d = new Date(2010,10,8);
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, 1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());
Marko Bonaci
  • 5,622
  • 2
  • 34
  • 55
CleverPatrick
  • 9,261
  • 5
  • 63
  • 86
15

You first need to parse your string before following the other people's suggestion:

var dateString = "2010-09-11";
var myDate = new Date(dateString);

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

If you want it back in the same format again you will have to do that "manually":

var y = myDate.getFullYear(),
    m = myDate.getMonth() + 1, // january is month 0 in javascript
    d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");

But I suggest getting Date.js as mentioned in other replies, that will help you alot.

einarmagnus
  • 3,507
  • 1
  • 21
  • 31
11

I feel that nothing is safer than .getTime() and .setTime(), so this should be the best, and performant as well.

const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS

.setDate() for invalid Date (like 31 + 1) is too dangerous, and it depends on the browser implementation.

Polv
  • 1,918
  • 1
  • 20
  • 31
6

Getting the next 5 days:

var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();


for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}
tiny sunlight
  • 6,231
  • 3
  • 21
  • 42
fitodac
  • 61
  • 1
  • 1
4

Two methods:

1:

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)

2: Similar to the previous method

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)
Winter
  • 3,894
  • 7
  • 24
  • 56
Laksh Goel
  • 169
  • 1
  • 12
4

Via native JS, to add one day you may do following:

let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow

Another option is to use moment library:

const date = moment().add(14, "days").toDate()
Andrii Muzalevskyi
  • 3,261
  • 16
  • 20
  • 1
    Please explain what this code does. Add details about how it addresses the OP's problem. – Yash Sep 20 '19 at 09:33
2

Get the string value of the date using the dateObj.toJSON() method Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON Slice the date from the returned value and then increment by the number of days you want.

var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);
Philip E
  • 838
  • 9
  • 15
  • Date.toJSON uses UTC timezone http://stackoverflow.com/questions/11382606/javascript-date-tojson-dont-get-the-timezone-offset – AndreyP Apr 20 '17 at 12:33
2
 Date.prototype.AddDays = function (days) {
    days = parseInt(days, 10);
    return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}

Example

var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));

Result

2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z
swirekx
  • 31
  • 1
  • Your code does not work. I have tried it with the first console.log() and it says: dt.AddDays() is not a function. –  May 20 '19 at 11:59
1

Not entirelly sure if it is a BUG(Tested Firefox 32.0.3 and Chrome 38.0.2125.101), but the following code will fail on Brazil (-3 GMT):

Date.prototype.shiftDays = function(days){    
  days = parseInt(days, 10);
  this.setDate(this.getDate() + days);
  return this;
}

$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");

Result:

Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200

Adding one Hour to the date, will make it work perfectly (but does not solve the problem).

$date = new Date(2014, 9, 16,0,1,1);

Result:

Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200
Alan Weiss
  • 69
  • 6
1

Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.

  const tomorrow = () => {
      let t = new Date();
      t.setDate(t.getDate() + 1);
      return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
        t.getDate()
      ).padStart(2, '0')}`;
    };
    tomorrow();
Gor
  • 1,385
  • 12
  • 7
1

Incrementing date's year with vanilla js:

start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020

Just in case someone wants to increment other value than the date (day)

d1jhoni1b
  • 7,497
  • 1
  • 51
  • 37
1

Timezone/daylight savings aware date increment for JavaScript dates:

function nextDay(date) {
    const sign = v => (v < 0 ? -1 : +1);
    const result = new Date(date.getTime());
    result.setDate(result.getDate() + 1);
    const offset = result.getTimezoneOffset();
    return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}
Peter Marklund
  • 1,033
  • 10
  • 9
1

This a simpler method , and it will return the date in simple yyyy-mm-dd format , Here it is

function incDay(date, n) {
    var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
    fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
    return fudate;
}

example :

var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .

Note

incDay(new Date("2020-11-12"), 1); 
incDay("2020-11-12", 1); 

will return the same result .

Solyman
  • 11
  • 1
0

Use this function, it´s solved my problem:

    let nextDate = (daysAhead:number) => {
      const today = new Date().toLocaleDateString().split('/')
      const invalidDate = new Date(`${today[2]}/${today[1]}/${Number(today[0])+daysAhead}`)
      if(Number(today[1]) === Number(12)){
        return new Date(`${Number(today[2])+1}/${1}/${1}`)
      }
      if(String(invalidDate) === 'Invalid Date'){
        return new Date(`${today[2]}/${Number(today[1])+1}/${1}`)
      }
        return new Date(`${today[2]}/${Number(today[1])}/${Number(today[0])+daysAhead}`)
    }
NicholasWM
  • 106
  • 1
  • 2
0

Assigning the Increment of current date to other Variable

 let startDate=new Date();
 let endDate=new Date();    
 endDate.setDate(startDate.getDate() + 1)
 console.log(startDate,endDate)
venky07
  • 81
  • 1
  • 2
0

There is a popular library called MomentJS for manipulating date and time easily with functions in human readable form. For incrementing a date you can ref to example below:-

// For current date const date = moment();
const date = moment('2023-07-22');
const incrementedDate = date.add(1, 'days');

I hope this solves the question in more efficient way and for more detailed view and for more functions of MomentJS you can check the link

https://codingeagles.com/the-ultimate-guide-for-working-with-date-and-time-with-momentjs/

Rajan Garg
  • 19
  • 2