How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?
- I have a JS code that showing the actually date +1 (the tomorrows date). If the day is the 31st, then 32 appears as the date instead of the 1st. How can I fix this? Here is the code: var date = new Date(); var current_date = (date.getDate()+1)+"-"+(date.getMonth()+1)+"-"+ date.getFullYear(); document.getElementById("p1").innerHTML = current_date; I need only the correct tomorrow date. ThanksKlausi– Klausi2025-10-31 14:05:16 +00:00Commented Oct 31 at 14:05
56 Answers
You can create one using Date.prototype.setDate():
Date.prototype.addDays = function(days) { var date = new Date(this.valueOf()); date.setDate(date.getDate() + days); return date; } var date = new Date(); console.log(date.addDays(5)); This takes care of automatically incrementing the month if necessary, as noted here. For example:
8/31 + 1 day will become 9/1.
The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.
26 Comments
Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};864E5 for some reason I prefer to write 24*60*60 in my code :)Correct Answer:
function addDays(date, days) { var result = new Date(date); result.setDate(result.getDate() + days); return result; } Incorrect Answer:
This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.
// Don't do it this way! function addDaysWRONG(date, days) { var result = new Date(); // not instatiated with date!!! DANGER result.setDate(date.getDate() + days); return result; } Proof / Example
// Correct function addDays(date, days) { var result = new Date(date); result.setDate(result.getDate() + days); return result; } // Bad Year/Month function addDaysWRONG(date, days) { var result = new Date(); result.setDate(date.getDate() + days); return result; } // Bad during DST function addDaysDstFail(date, days) { var dayms = (days * 24 * 60 * 60 * 1000); return new Date(date.getTime() + dayms); } // TEST function formatDate(date) { return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); } $('tbody tr td:first-child').each(function () { var $in = $(this); var $out = $('<td/>').insertAfter($in).addClass("answer"); var $outFail = $('<td/>').insertAfter($out); var $outDstFail = $('<td/>').insertAfter($outFail); var date = new Date($in.text()); var correctDate = formatDate(addDays(date, 1)); var failDate = formatDate(addDaysWRONG(date, 1)); var failDstDate = formatDate(addDaysDstFail(date, 1)); $out.text(correctDate); $outFail.text(failDate); $outDstFail.text(failDstDate); $outFail.addClass(correctDate == failDate ? "right" : "wrong"); $outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong"); }); body { font-size: 14px; } table { border-collapse:collapse; } table, td, th { border:1px solid black; } td { padding: 2px; } .wrong { color: red; } .right { color: green; } .answer { font-weight: bold; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody> <tr> <th colspan="4">DST Dates</th> </tr> <tr> <th>Input</th> <th>+1 Day</th> <th>+1 Day Fail</th> <th>+1 Day DST Fail</th> </tr> <tr><td>03/10/2013</td></tr> <tr><td>11/03/2013</td></tr> <tr><td>03/09/2014</td></tr> <tr><td>11/02/2014</td></tr> <tr><td>03/08/2015</td></tr> <tr><td>11/01/2015</td></tr> <tr> <th colspan="4">2013</th> </tr> <tr> <th>Input</th> <th>+1 Day</th> <th>+1 Day Fail</th> <th>+1 Day DST Fail</th> </tr> <tr><td>01/01/2013</td></tr> <tr><td>02/01/2013</td></tr> <tr><td>03/01/2013</td></tr> <tr><td>04/01/2013</td></tr> <tr><td>05/01/2013</td></tr> <tr><td>06/01/2013</td></tr> <tr><td>07/01/2013</td></tr> <tr><td>08/01/2013</td></tr> <tr><td>09/01/2013</td></tr> <tr><td>10/01/2013</td></tr> <tr><td>11/01/2013</td></tr> <tr><td>12/01/2013</td></tr> <tr> <th colspan="4">2014</th> </tr> <tr> <th>Input</th> <th>+1 Day</th> <th>+1 Day Fail</th> <th>+1 Day DST Fail</th> </tr> <tr><td>01/01/2014</td></tr> <tr><td>02/01/2014</td></tr> <tr><td>03/01/2014</td></tr> <tr><td>04/01/2014</td></tr> <tr><td>05/01/2014</td></tr> <tr><td>06/01/2014</td></tr> <tr><td>07/01/2014</td></tr> <tr><td>08/01/2014</td></tr> <tr><td>09/01/2014</td></tr> <tr><td>10/01/2014</td></tr> <tr><td>11/01/2014</td></tr> <tr><td>12/01/2014</td></tr> <tr> <th colspan="4">2015</th> </tr> <tr> <th>Input</th> <th>+1 Day</th> <th>+1 Day Fail</th> <th>+1 Day DST Fail</th> </tr> <tr><td>01/01/2015</td></tr> <tr><td>02/01/2015</td></tr> <tr><td>03/01/2015</td></tr> <tr><td>04/01/2015</td></tr> <tr><td>05/01/2015</td></tr> <tr><td>06/01/2015</td></tr> <tr><td>07/01/2015</td></tr> <tr><td>08/01/2015</td></tr> <tr><td>09/01/2015</td></tr> <tr><td>10/01/2015</td></tr> <tr><td>11/01/2015</td></tr> <tr><td>12/01/2015</td></tr> </tbody> </table> 21 Comments
new Date(date.getTime()); is better but I don't think there is any case where new Date(date) will give a wrong answer due to string conversion. If anyone can provide an example I'd like to see it. How crazy would it be for a date constructor to not read the string the same way it is formatted to by default. From what I understand, the user's local timezone and date format settings should have no affect on the correctness of this function.new Date(); vs new Date(date). The first creates with the current year, month, and day; and then changes the day. The second creates a date with the given year, month, day, and then changes the day.var today = new Date(); var tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); console.log(today); console.log(tomorrow); Be careful, because this can be tricky. When setting tomorrow, it only works because its current value matches the year and month for today. However, setting to a date number like "32" normally will still work just fine to move it to the next month.
9 Comments
var d = new Date(); d.setDate( d.getDate() + 1 );?getDate() returns the day of that year. Then, calling setDate sets the day in the current year. So it is NOT a good general solution. @AnthonyWJones's answer actually works correctly.Date objects with new will fail if performed just when switching between months. today.getDate() would return the last day of the month, while tomorrows month would already be in the next month. So tomorrow would end up completely wrong.var d = new Date(2015,11,30);d.setDate(d.getDate() + 370) gives 3 Jan 2017 which crosses 2 years.These answers seem confusing to me, I prefer:
var ms = new Date().getTime() + 86400000; var tomorrow = new Date(ms); getTime() gives us milliseconds since 1970, and 86400000 is the number of milliseconds in a day. Hence, ms contains milliseconds for the desired date.
Using the millisecond constructor gives the desired date object.
7 Comments
new Date(new Date('11/4/2012').getTime() + 86400000)My simple solution is:
nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1); this solution does not have problem with daylight saving time. Also, one can add/sub any offset for years, months, days etc.
day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61); is correct code.
6 Comments
setDate.Here is the way that use to add days, months, and years for a particular date in Javascript.
// To add Days var d = new Date(); d.setDate(d.getDate() + 5); // To add Months var m = new Date(); m.setMonth(m.getMonth() + 5); // To add Years var y = new Date(); y.setFullYear(y.getFullYear() + 5); Comments
Try
var someDate = new Date(); var duration = 2; //In Days someDate.setTime(someDate.getTime() + (duration * 24 * 60 * 60 * 1000)); Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.
4 Comments
setDate()? Is it this: stackoverflow.com/questions/5497637/…The simplest approach that I have implemented is to use Date() itself. `
const days = 15; // Date.now() gives the epoch date value (in milliseconds) of current date nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000) `
2 Comments
Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.
If you want to just simply add n days to the date you have you are best to just go:
myDate.setDate(myDate.getDate() + n);
or the longwinded version
var theDate = new Date(2013, 11, 15); var myNewDate = new Date(theDate); myNewDate.setDate(myNewDate.getDate() + 30); console.log(myNewDate); This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.
1 Comment
int days = 1; var newDate = new Date(Date.now() + days * 24*60*60*1000); var days = 2; var newDate = new Date(Date.now() + days * 24*60*60*1000); document.write('Today: <em>'); document.write(new Date()); document.write('</em><br/> New: <strong>'); document.write(newDate); 3 Comments
If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:
var nextWeek = moment().add(7, 'days'); alert(nextWeek); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script> Reference: http://momentjs.com/docs/#/manipulating/add/
11 Comments
the simplest answer is, assuming the need is to add 1 day to the current date:
var currentDate = new Date(); var numberOfDayToAdd = 1; currentDate.setDate(currentDate.getDate() + numberOfDayToAdd ); To explain to you, line by line, what this code does:
- Create the current date variable named currentDate. By default "new Date()" automatically assigns the current date to the variable.
- Create a variable to save the number of day(s) to add to the date (you can skip this variable and use directly the value in the third line)
- Change the value of Date (because Date is the number of the month's day saved in the object) by giving the same value + the number you want. The switch to the next month will be automatic
1 Comment
I created these extensions last night:
you can pass either positive or negative values;
example:
var someDate = new Date(); var expirationDate = someDate.addDays(10); var previous = someDate.addDays(-5); Date.prototype.addDays = function (num) { var value = this.valueOf(); value += 86400000 * num; return new Date(value); } Date.prototype.addSeconds = function (num) { var value = this.valueOf(); value += 1000 * num; return new Date(value); } Date.prototype.addMinutes = function (num) { var value = this.valueOf(); value += 60000 * num; return new Date(value); } Date.prototype.addHours = function (num) { var value = this.valueOf(); value += 3600000 * num; return new Date(value); } Date.prototype.addMonths = function (num) { var value = new Date(this.valueOf()); var mo = this.getMonth(); var yr = this.getYear(); mo = (mo + num) % 12; if (0 > mo) { yr += (this.getMonth() + num - mo - 12) / 12; mo += 12; } else yr += ((this.getMonth() + num - mo) / 12); value.setMonth(mo); value.setYear(yr); return value; } 3 Comments
A solution designed for the pipeline operator:
const addDays = days => date => { const result = new Date(date); result.setDate(result.getDate() + days); return result; }; Usage:
// Without the pipeline operator... addDays(7)(new Date()); // And with the pipeline operator... new Date() |> addDays(7); If you need more functionality, I suggest looking into the date-fns library.
Comments
Short:
function addDays(date, number) { const newDate = new Date(date); return new Date(newDate.setDate(newDate.getDate() + number)); } console.log({ tomorrow: addDays(new Date(), 1) }); Advance:
function addDays(date, number) { const newDate = new Date(date); return new Date(newDate.setDate(date.getDate() + number)); } function addMonths(date, number) { const newDate = new Date(date); return new Date(newDate.setMonth(newDate.getMonth() + number)); } function addYears(date, number) { const newDate = new Date(date); return new Date(newDate.setFullYear(newDate.getFullYear() + number)); } function getNewDate(dateTime) { let date = new Date(); let number = parseInt(dateTime.match(/\d+/)[0]); if (dateTime.indexOf('-') != -1) number = (-number); if (dateTime.indexOf('day') != -1) date = addDays(date, number); else if (dateTime.indexOf('month') != -1) date = addMonths(date, number); else if (dateTime.indexOf('year') != -1) date = addYears(date, number); return date; } console.log({ tomorrow: getNewDate('+1day'), yesterday: getNewDate('-1day'), nextMonth: getNewDate('+1month'), nextYear: getNewDate('+1year'), }); With fix provide by jperl
2 Comments
addDays(today, 1), today will now be tomorrow. function addDays(date, number) { const newDate = new Date(date) return new Date(newDate.setDate(newDate.getDate() + number)); }return newDate? Why is this double-wrapping is used?You can try:
var days = 50; const d = new Date(); d.setDate(d.getDate() + days) This should work well.
1 Comment
The simplest solution.
Date.prototype.addDays = function(days) { this.setDate(this.getDate() + parseInt(days)); return this; }; // and then call var newDate = new Date().addDays(2); //+2 days console.log(newDate); // or var newDate1 = new Date().addDays(-2); //-2 days console.log(newDate1); 1 Comment
to substract 30 days use (24h=86400000ms)
new Date(+yourDate - 30 *86400000) var yourDate=new Date(); var d = new Date(+yourDate - 30 *86400000) console.log(d) 1 Comment
Late to the party, but if you use there's an excellent plugin called Moment:jQuery then
var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate(); http://momentjs.com/docs/#/manipulating/
And lots of other good stuff in there!
Edit: jQuery reference removed thanks to aikeru's comment
5 Comments
You can use JavaScript, no jQuery required:
var someDate = new Date(); var numberOfDaysToAdd = 6; someDate.setDate(someDate.getDate() + numberOfDaysToAdd); Formatting to dd/mm/yyyy : var dd = someDate.getDate(); var mm = someDate.getMonth() + 1; var y = someDate.getFullYear(); var someFormattedDate = dd + '/'+ mm + '/'+ y; 1 Comment
Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :
Date.prototype.addDays = function(days){ var ms = new Date().getTime() + (86400000 * days); var added = new Date(ms); return added; } 2 Comments
I had issues with daylight savings time with the proposed solution.
By using getUTCDate / setUTCDate instead, I solved my issue.
// Curried, so that I can create helper functions like `add1Day` const addDays = num => date => { // Make a working copy so we don't mutate the supplied date. const d = new Date(date); d.setUTCDate(d.getUTCDate() + num); return d; } Comments
As simple as this:
new Date((new Date()).getTime() + (60*60*24*1000)); 1 Comment
Why so complicated?
Let's assume you store the number of days to add in a variable called days_to_add.
Then this short one should do it:
calc_date = new Date(Date.now() +(days_to_add * 86400000)); With Date.now() you get the actual unix timestamp as milliseconds and then you add as many milliseconds as you want to add days to. One day is 24h60min60s*1000ms = 86400000 ms or 864E5.
1 Comment
Old I know, but sometimes I like this:
function addDays(days) { return new Date(Date.now() + 864e5 * days); } 3 Comments
Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};The mozilla docs for setDate() don't indicate that it will handle end of month scenarios. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
setDate()
- Sets the day of the month (1-31) for a specified date according to local time.
That is why I use setTime() when I need to add days.
I guess I'll give an answer as well:
Personally, I like to attempt to avoid gratuitous variable declaration, method calls, and constructor calls, as they are all expensive on performance. (within reason, of course)
I was going to leave this as just comment under the Answer given by @AnthonyWJones but thought better of it.
// Prototype usage... Date.prototype.addDays = Date.prototype.addDays || function( days ) { return this.setTime( 864E5 * days + this.valueOf() ) && this; }; // Namespace usage... namespace.addDaysToDate = function( date, days ) { return date.setTime( 864E5 * days + date.valueOf() ) && date; }; // Basic Function declaration... function addDaysToDate( date, days ) { return date.setTime( 864E5 * days + date.valueOf() ) && date; }; The above will respect DST. Meaning if you add a number of days that cross DST, the displayed time (hour) will change to reflect that.
Example:
Nov 2, 2014 02:00 was the end of DST.
var dt = new Date( 2014, 10, 1, 10, 30, 0 ); console.log( dt ); // Sat Nov 01 2014 10:30:00 console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 09:30:00 If you're looking to retain the time across DST (so 10:30 will still be 10:30)...
// Prototype usage... Date.prototype.addDays = Date.prototype.addDays || function( days ) { return this.setDate( this.getDate() + days ) && this; }; // Namespace usage... namespace.addDaysToDate = function( date, days ) { return date.setDate( date.getDate() + days ) && date; }; // Basic Function declaration... function addDaysToDate( date, days ) { return date.setDate( date.getDate() + days ) && date; }; So, now you have...
var dt = new Date( 2014, 10, 1, 10, 30, 0 ); console.log( dt ); // Sat Nov 01 2014 10:30:00 console.log( dt.addDays( 10 ) ); // Tue Nov 11 2014 10:30:00