How to add days to current Date
using JavaScript? Does JavaScript have a built in function like .NET's AddDay()
?
You can create one with:-
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. 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.
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();
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 = $('
DST Dates | |||
---|---|---|---|
Input | +1 Day | +1 Day Fail | +1 Day DST Fail |
03/10/2013 | |||
11/03/2013 | |||
03/09/2014 | |||
11/02/2014 | |||
03/08/2015 | |||
11/01/2015 | |||
2013 | |||
Input | +1 Day | +1 Day Fail | +1 Day DST Fail |
01/01/2013 | |||
02/01/2013 | |||
03/01/2013 | |||
04/01/2013 | |||
05/01/2013 | |||
06/01/2013 | |||
07/01/2013 | |||
08/01/2013 | |||
09/01/2013 | |||
10/01/2013 | |||
11/01/2013 | |||
12/01/2013 | |||
2014 | |||
Input | +1 Day | +1 Day Fail | +1 Day DST Fail |
01/01/2014 | |||
02/01/2014 | |||
03/01/2014 | |||
04/01/2014 | |||
05/01/2014 | |||
06/01/2014 | |||
07/01/2014 | |||
08/01/2014 | |||
09/01/2014 | |||
10/01/2014 | |||
11/01/2014 | |||
12/01/2014 | |||
2015 | |||
Input | +1 Day | +1 Day Fail | +1 Day DST Fail |
01/01/2015 | |||
02/01/2015 | |||
03/01/2015 | |||
04/01/2015 | |||
05/01/2015 | |||
06/01/2015 | |||
07/01/2015 | |||
08/01/2015 | |||
09/01/2015 | |||
10/01/2015 | |||
11/01/2015 | |||
12/01/2015 |
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);
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.
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.
var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
gives 3 Jan 2017 which crosses 2 years.
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.
setDate
.
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.
new Date(new Date('11/4/2012').getTime() + 86400000)
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);
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.
setDate()
? Is it this: stackoverflow.com/questions/5497637/…
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.
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)
`
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: ');
document.write(new Date());
document.write('
New: ');
document.write(newDate);
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);
Reference: http://momentjs.com/docs/#/manipulating/add/
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;
}
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.
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
Without using the second variable, you can replace 7 with your next x days:
let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));
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)
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);
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
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;
As simple as this:
new Date((new Date()).getTime() + (60*60*24*1000));
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;
}
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
You can try:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
This should work well.
No, javascript has no a built in function, but you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
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;
}
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.
Generic prototype with no variables, it applies on an existing Date value:
Date.prototype.addDays = function (days) {
return new Date(this.valueOf() + days * 864e5);
}
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
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
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)); }
Success story sharing
Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
864E5
for some reason I prefer to write24*60*60
in my code :)