124

I am sure that a lot of people asked this question but when I checked the answers it seems to me that they are wrong that what I found

var startDate = new Date(Date.parse(startdate));
//The start date is right lets say it is 'Mon Jun 30 2014 00:00:00'

var endDate = new Date(startDate.getDate() + 1);
// the enddate in the console will be 'Wed Dec 31 1969 18:00:00' and that's wrong it should be  1 july 

I know that .getDate() return from 1-31 but Does the browser or the javascript increase only the day without updating the month and the year ?

and in this case Should I write an algorithm to handle this ? or there is another way ?

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
kartal
  • 17,436
  • 34
  • 100
  • 145

14 Answers14

219

Note that Date.getDate only returns the day of the month. You can add a day by calling Date.setDate and appending 1.

// Create new Date instance
var date = new Date()

// Add a day
date.setDate(date.getDate() + 1)

JavaScript will automatically update the month and year for you.

EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.

Aeveus
  • 5,052
  • 3
  • 30
  • 42
  • 3
    This seems to add only 23 hours sometimes. Is there some reason that might happen? – Jonathan W. Mar 24 '20 at 23:06
  • 1
    Aha, it only adds 23 hours across the change from Standard time to Daylight time. Too bad it doesn't update hours in addition to months and years. I'll try forcing UTC (it seems to default to locale timezone?). – Jonathan W. Mar 24 '20 at 23:28
  • Try using Date.prototype.setUTCDate() if you want to avoid timezone conversions. More details on Mozilla Web Docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCDate – Ehsan Kazi Jun 19 '22 at 10:40
36

The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.

Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.

A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.

For example,

var dateString = 'Mon Jun 30 2014 00:00:00';

var startDate = new Date(dateString);

// seconds * minutes * hours * milliseconds = 1 day 
var day = 60 * 60 * 24 * 1000;

var endDate = new Date(startDate.getTime() + day);

JSFiddle

Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.

Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
  • 2
    this solution does not consider "day saving" changes, when a day may happens to be an hour longer or shorter. – qwertzui11 Oct 16 '17 at 06:43
  • You are correct. I will add a note in my answer that states this, but as of right now the clear best solution is to not role your own when lightweight libraries like moment.js exist to avoid these edge cases without fuss. This is one way to handle the general case in 2 lines. – Austin Brunkhorst Oct 17 '17 at 04:28
12

There is issue of 31st and 28th Feb with getDate() I use this function getTime and 24*60*60*1000 = 86400000

Use this function:


    function incrementDate(dateInput,increment) {
        var dateFormatTotime = new Date(dateInput);
        var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
        return increasedDate;
    }

Example as below:

var dateWith31 = new Date("2017-08-31");
var dateWith29 = new Date("2016-02-29");

var amountToIncreaseWith = 1; //Edit this number to required input

console.log(incrementDate(dateWith31,amountToIncreaseWith));
console.log(incrementDate(dateWith29,amountToIncreaseWith));

function incrementDate(dateInput,increment) {
        var dateFormatTotime = new Date(dateInput);
        var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
        return increasedDate;
    }
Black Mamba
  • 13,632
  • 6
  • 82
  • 105
5

I think what you are looking for is:

startDate.setDate(startDate.getDate() + 1);

Also, you can have a look at Moment.js

A javascript date library for parsing, validating, manipulating, and formatting dates.

HJ05
  • 1,358
  • 2
  • 11
  • 23
5

use this i think it is useful for you

var endDate=startDate.setDate(startDate.getDate() + 1);
4

i know it's been long time since this is posted but here's my answer

function addDays(date, n)
{
  const oneDayInMs = 86400 * 1000;
  return new Date(Date.parse(date) + (n * oneDayInMs));
}
addDays(new Date(), 1);
abel-mak
  • 121
  • 1
  • 4
3
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);

This will help you...

3

add one day in javascript in one line

NB: if you want to add a specific number of days ... just replace 1 with the number of days you want


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

console.log(new Date(new Date().setDate(new Date().getDate() + 1)))
MgCodeur
  • 31
  • 2
2

Just for the sake of adding functions to the Date prototype:

In a mutable fashion / style:

Date.prototype.addDays = function(n) {
   this.setDate(this.getDate() + n);
};

// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
   this.addDays(1);
};

Date.prototype.addMonths = function(n) {
   this.setMonth(this.getMonth() + n);
};

Date.prototype.addYears = function(n) {
   this.setFullYear(this.getFullYear() + n);
}

// etc...

var currentDate = new Date();
currentDate.nextDay();
Natalie Perret
  • 8,013
  • 12
  • 66
  • 129
0

If you don't mind using a library, DateJS (https://github.com/abritinthebay/datejs/) would make this fairly easy. You would probably be better off with one of the answers using vanilla JavaScript however, unless you're going to take advantage of some other DateJS features like parsing of unusually-formatted dates.

If you're using DateJS a line like this should do the trick:

Date.parse(startdate).add(1).days();

You could also use MomentJS which has similar features (http://momentjs.com/), however I'm not as familiar with it.

Ectropy
  • 1,533
  • 4
  • 20
  • 37
0

The below will add a single day to a current time. I believe this will handle daylight saving times, etc.

function increment_date (date) {
    let old_date = new Date (date);
    date.setDate (old_date.getDate() + 1);
    while (date.getDate() == old_date.getDate()) {
        date.setHours (date.getHours() + 1);
    }
    date.setHours (0);
}    
eff
  • 385
  • 2
  • 8
0

add one day in javascript in one line

// just replace 1 with the number of days you want

let tomorrow = new Date(new Date().getTime() + ((1 * 24) * 60 * 60 * 1000));

console.log("tomorrow ", tomorrow)
MgCodeur
  • 31
  • 2
0

Adding one day in existing date.

var current_date  = new Date();  
 console.log("current_date", current_date);
 var new_date = new Date(current_date.setDate(current_date.getDate()+1));
  console.log("new_date", new_date);

hope it will work.

Manoj Gupta
  • 456
  • 4
  • 9
0

Based on the answers of this thread, I came up with the following function. It does not rely on any third party libraries.

For the project that I'm working on I needed the dates formatted as MM/DD/YYYY and also to include both starting and ending date in the array. However, you can format the results as per your wish. You may want to read this answer regarding how to format dates.

function getDatesBetween(startDate, _endDate) {
  var endDate = new Date(
    new Date(_endDate).setDate(new Date(_endDate).getDate() + 1),
  );
  var oneDay = 24 * 3600 * 1000;

  for (
    var result = [],
      init = new Date(startDate) * 1,
      last = new Date(endDate) * 1;
    init < last;
    init += oneDay
  ) {
    result.push(new Date(init).toLocaleDateString("en-US"));
  }

  return result;
}

//example

var start = "12/26/2023";
var end = "12/30/2023";

getDatesBetween( start, end ) //['12/26/2023', '12/27/2023', '12/28/2023', '12/29/2023', '12/30/2023']

Diego Fortes
  • 8,830
  • 3
  • 32
  • 42