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
Check this JsFiddle
// 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>
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.
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.
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.
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.
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);
CodePen
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);
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/
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
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.
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);
You can try:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
This should work well.
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;
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
Late to the party, but if you use jQuery then there's an excellent plugin called Moment:
http://momentjs.com/
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
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);
}
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
Related
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
Check this JsFiddle
// 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>
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.
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.
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.
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.
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);
CodePen
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);
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/
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
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.
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);
You can try:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
This should work well.
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;
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
Late to the party, but if you use jQuery then there's an excellent plugin called Moment:
http://momentjs.com/
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
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);
}
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
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
Check this JsFiddle
// 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>
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.
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.
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.
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.
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);
CodePen
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);
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/
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
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.
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);
You can try:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
This should work well.
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;
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
Late to the party, but if you use jQuery then there's an excellent plugin called Moment:
http://momentjs.com/
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
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);
}
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
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?
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();
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
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);
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)
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());
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.
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.
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)
}
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)
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()
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);
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
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
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();
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)
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);
}
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 .
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}`)
}
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)
I've a var example = "05-10-1983"
How I can get the "next day" of the string example?
I've try to use Date object...but nothing...
This would do it for simple scenarios like the one you have:
var example = '05-10-1983';
var date = new Date();
var parts = example.split('-');
date.setFullYear(parts[2], parts[0]-1, parts[1]); // year, month (0-based), day
date.setTime(date.getTime() + 86400000);
alert(date);
Essentially, we create an empty Date object and set the year, month, and date with the setFullYear() function. We then grab the timestamp from that date using getTime() and add 1 day (86400000 milliseconds) to it and set it back to the date using the setTime() function.
If you need something more complicated than this, like support for different formats and stuff like that, you should take a look at the datejs library which does quite a bit of work for you.
You can do the following:
var nextDay;
var example = "05-10-1983";
nextDay = new Date(example);
nextDay.setDate(nextDay.getDate() + 1);
#getDate/#setDate gets/sets the current day of the month (1-31).
After the above is run, nextDay will be set to whatever tomorrow's date is. This will also rollover to the next month / year if it's the end of the month, and even handle leap years. :)
new Date(+new Date('05-10-1983'.replace(/-/g,'/')) + 24*60*60*1000)
The problem with the +86400000 approach is the potential for error when crossing a daylight savings time barrier.
For example, I'm on EST.
If I do this:
var d = new Date("11/04/2012 00:00:00");
var e = new Date(d.getTime() + 86400000);
e is going to be 11/4/2012 23:00:00
If you then extract just the date portion, you get the wrong value. I recently hit upon this issue while writing a calendar control.
this will do it better (and with a flexible offset which will let you do more than 1 day in the future):
function getTomorrow(d,offset) {
if (!offset) { offset = 1 }
return new Date(new Date().setDate(d.getDate() + offset));
}
So
var d = new Date("11/04/2012 00:00:00");
var e = new Date(d.getTime() + 86400000);
doesn't work because of daylight saving barriers. I ran into the same problem. I ended up doing something like this:
function next_day(date) {
var e = new Date(date.getTime() + 24 * 60 * 60 * 1000);
if e.getHours() != date.getHours() {
e = new Date(e.getTime() + (e.getHours() - date.getHours()) * 60 * 60 * 1000)
}
return e;
}
You can use framework called php.js. Google for it. This includes the advanced date functions and more
You can find out day index by getDay() function and create an array of days strings in following manner-
day = new Date(YourDate);
var dayArray = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
day = dayArray[day.getDay()+1];
There are leap seconds, leap days, DST, etc., so this can be a tricky problem to solve in all cases.
In my opinion, the best way to address this (without a date library) is to take advantage of the Date constructor overflow feature[1]:
main();
function main() {
var date = uniqueDateParse( '05-10-1983' );
var newDate = nextDay( date );
print( date );
print( newDate );
}
function uniqueDateParse( string ) {
var stringArray = string.split( '-', 3 );
var month = stringArray[ 0 ],
day = stringArray[ 1 ],
year = stringArray[ 2 ];
// Per ISO 8601[2], using Pacific Daylight Time[3].
var dateString = year + '-' + month + '-' + day + 'T00:00:00-07:00';
return new Date( dateString );
}
function nextDay( date ) {
return new Date( date.getFullYear()
, date.getMonth()
, date.getDate() + 1 );
}
function print( object ) {
console.log( object );
}
Links
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters
[2] http://www.w3.org/TR/NOTE-datetime
[3] http://www.timeanddate.com/time/zones/pdt
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Is there an easy way of taking a olain JavaScript Date (e.g. today) and going back X days?
So, for example, if I want to calculate the date 5 days before today.
Try something like this:
var d = new Date();
d.setDate(d.getDate()-5);
Note that this modifies the date object and returns the time value of the updated date.
var d = new Date();
document.write('Today is: ' + d.toLocaleString());
d.setDate(d.getDate() - 5);
document.write('<br>5 days ago was: ' + d.toLocaleString());
var dateOffset = (24*60*60*1000) * 5; //5 days
var myDate = new Date();
myDate.setTime(myDate.getTime() - dateOffset);
If you're performing lots of headachy date manipulation throughout your web application, DateJS will make your life much easier:
http://simonwillison.net/2007/Dec/3/datejs/
It goes something like this:
var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);
I noticed that the getDays+ X doesn't work over day/month boundaries. Using getTime works as long as your date is not before 1970.
var todayDate = new Date(), weekDate = new Date();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));
If you want it all on one line instead.
5 days from today
//past
var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));
5 days from a specific date
var pastDate = new Date('2019-12-12T00:00:00');
//past
var fiveDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));
I wrote a function you can use.
function AddOrSubractDays(startingDate, number, add) {
if (add) {
return new Date(new Date().setDate(startingDate.getDate() + number));
} else {
return new Date(new Date().setDate(startingDate.getDate() - number));
}
}
console.log('Today : ' + new Date());
console.log('Future : ' + AddOrSubractDays(new Date(), 5, true));
console.log('Past : ' + AddOrSubractDays(new Date(), 5, false));
I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.
Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.
So, for your particular question:
today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))
Works like a charm.
I use this method all the time for doing rolling 30/60/365 day calculations.
You can easily extrapolate this to create units of time for months, years, etc.
get moment.js. All the cool kids use it. It has more formatting options, etc. Where
var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');
Optional! Convert to JS Date obj for Angular binding.
var date = new Date(dateMnsFive.toISOString());
Optional! Format
var date = dateMnsFive.format("YYYY-MM-DD");
A few of the existing solutions were close, but not quite exactly what I wanted. This function works with both positive or negative values and handles boundary cases.
function addDays(date, days) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() + days,
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
Without using the second variable, you can replace 7 for with your back x days:
let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))
I made this prototype for Date so that I could pass negative values to subtract days and positive values to add days.
if(!Date.prototype.adjustDate){
Date.prototype.adjustDate = function(days){
var date;
days = days || 0;
if(days === 0){
date = new Date( this.getTime() );
} else if(days > 0) {
date = new Date( this.getTime() );
date.setDate(date.getDate() + days);
} else {
date = new Date(
this.getFullYear(),
this.getMonth(),
this.getDate() - Math.abs(days),
this.getHours(),
this.getMinutes(),
this.getSeconds(),
this.getMilliseconds()
);
}
this.setTime(date.getTime());
return this;
};
}
So, to use it i can simply write:
var date_subtract = new Date().adjustDate(-4),
date_add = new Date().adjustDate(4);
I like doing the maths in milliseconds. So use Date.now()
var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds
and if you like it formatted
new Date(newDate).toString(); // or .toUTCString or .toISOString ...
NOTE: Date.now() doesn't work in older browsers (eg IE8 I think). Polyfill here.
UPDATE June 2015
#socketpair pointed out my sloppiness. As s/he says "Some day in year have 23 hours, and some 25 due to timezone rules".
To expand on that, the answer above will have daylightsaving inaccuracies in the case where you want to calculate the LOCAL day 5 days ago in a timezone with daylightsaving changes and you
assume (wrongly) that Date.now() gives you the current LOCAL now time, or
use .toString() which returns the local date and therefore is incompatible with the Date.now() base date in UTC.
However, it works if you're doing your math all in UTC, eg
A. You want the UTC date 5 days ago from NOW (UTC)
var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds UTC
new Date(newDate).toUTCString(); // or .toISOString(), BUT NOT toString
B. You start with a UTC base date other than "now", using Date.UTC()
newDate = new Date(Date.UTC(2015, 3, 1)).getTime() + -5*24*3600000;
new Date(newDate).toUTCString(); // or .toISOString BUT NOT toString
split your date into parts, then return a new Date with the adjusted values
function DateAdd(date, type, amount){
var y = date.getFullYear(),
m = date.getMonth(),
d = date.getDate();
if(type === 'y'){
y += amount;
};
if(type === 'm'){
m += amount;
};
if(type === 'd'){
d += amount;
};
return new Date(y, m, d);
}
Remember that the months are zero based, but the days are not. ie new Date(2009, 1, 1) == 01 February 2009, new Date(2009, 1, 0) == 31 January 2009;
Some people suggested using moment.js to make your life easier when handling dates in js. Time has passed since those answers and it is noteworthy, that the authors of moment.js now discourage its use. Mainly due to its size and lack of tree-shaking-support.
If you want to go the library route, use an alternative like Luxon. It is significantly smaller (because of its clever use of the Intl object and support for tree-shaking) and just as versatile as moment.js.
To go back 5 days from today in Luxon, you would do:
import { DateTime } from 'luxon'
DateTime.now().minus({ days: 5 });
function addDays (date, daysToAdd) {
var _24HoursInMilliseconds = 86400000;
return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds);
};
var now = new Date();
var yesterday = addDays(now, - 1);
var tomorrow = addDays(now, 1);
See the following code, subtract the days from the current date. Also, set the month according to substracted date.
var today = new Date();
var substract_no_of_days = 25;
today.setTime(today.getTime() - substract_no_of_days* 24 * 60 * 60 * 1000);
var substracted_date = (today.getMonth()+1) + "/" +today.getDate() + "/" + today.getFullYear();
alert(substracted_date);
I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.
function dateManipulation(date, days, hrs, mins, operator) {
date = new Date(date);
if (operator == "-") {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() - durationInMs);
} else {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() + durationInMs);
}
return newDate;
}
Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");
Use MomentJS.
function getXDaysBeforeDate(referenceDate, x) {
return moment(referenceDate).subtract(x , 'day').format('MMMM Do YYYY, h:mm:ss a');
}
var yourDate = new Date(); // let's say today
var valueOfX = 7; // let's say 7 days before
console.log(getXDaysBeforeDate(yourDate, valueOfX));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
The top answers led to a bug in my code where on the first of the month it would set a future date in the current month. Here is what I did,
curDate = new Date(); // Took current date as an example
prvDate = new Date(0); // Date set to epoch 0
prvDate.setUTCMilliseconds((curDate - (5 * 24 * 60 * 60 * 1000))); //Set epoch time
I like the following because it is one line. Not perfect with DST changes but usually good enough for my needs.
var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));
Using Modern JavaScript function syntax
const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore));
console.log(getDaysPastDate(1)); // yesterday
A easy way to manage dates is use Moment.js
You can use add. Example
var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days'); //Add 5 days to start date
alert(new_date);
Docs http://momentjs.com/docs/#/manipulating/add/
for me all the combinations worked fine with below code snipplet ,
the snippet is for Angular-2 implementation ,
if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays
function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
d.getFullYear(),
d.getMonth(),
(d.getDate() + numberofDays)
);
}
I get good mileage out of date.js:
http://www.datejs.com/
d = new Date();
d.add(-10).days(); // subtract 10 days
Nice!
Website includes this beauty:
Datejs doesn’t just parse strings, it slices them cleanly in two
If you want to both subtract a number of days and format your date in a human readable format, you should consider creating a custom DateHelper object that looks something like this :
var DateHelper = {
addDays : function(aDate, numberOfDays) {
aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
return aDate; // Return the date
},
format : function format(date) {
return [
("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes
("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes
date.getFullYear() // Get full year
].join('/'); // Glue the pieces together
}
}
// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Subtract 5 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -5));
(see also this Fiddle)
To calculate relative time stamps with a more precise difference than whole days, you can use Date.getTime() and Date.setTime() to work with integers representing the number of milliseconds since a certain epoch—namely, January 1, 1970. For example, if you want to know when it’s 17 hours after right now:
const msSinceEpoch = (new Date()).getTime();
const fortyEightHoursLater = new Date(msSinceEpoch + 48 * 60 * 60 * 1000).toLocaleString();
const fortyEightHoursEarlier = new Date(msSinceEpoch - 48 * 60 * 60 * 1000).toLocaleString();
const fiveDaysAgo = new Date(msSinceEpoch - 120 * 60 * 60 * 1000).toLocaleString();
console.log({msSinceEpoch, fortyEightHoursLater, fortyEightHoursEarlier, fiveDaysAgo})
reference
function daysSinceGivenDate (date) {
const dateInSeconds = Math.floor((new Date().valueOf() - date.valueOf()) / 1000);
const oneDayInSeconds = 86400;
return Math.floor(dateInSeconds / oneDayInSeconds); // casted to int
};
console.log(daysSinceGivenDate(new Date())); // 0
console.log(daysSinceGivenDate(new Date("January 1, 2022 03:24:00"))); // relative...
First arg is the date to start with and second is how mush day you want to increase or reduce to the date
example (1)- pass -1 to reduce date by one day
example (2)- pass 1 to increase date by one day
const EditDay = (date: Date, num: number): Date => {
return new Date(date.getTime() + num * 24 * 60 * 60 * 1000)
}
When setting the date, the date converts to milliseconds, so you need to convert it back to a date:
This method also take into consideration, new year change etc.
function addDays( date, days ) {
var dateInMs = date.setDate(date.getDate() - days);
return new Date(dateInMs);
}
var date_from = new Date();
var date_to = addDays( new Date(), parseInt(days) );
You can using Javascript.
var CurrDate = new Date(); // Current Date
var numberOfDays = 5;
var days = CurrDate.setDate(CurrDate.getDate() + numberOfDays);
alert(days); // It will print 5 days before today
For PHP,
$date = date('Y-m-d', strtotime("-5 days")); // it shows 5 days before today.
echo $date;
Hope it will help you.
I converted into millisecond and deducted days else month and year won't change and logical
var numberOfDays = 10;//number of days need to deducted or added
var date = "01-01-2018"// date need to change
var dt = new Date(parseInt(date.substring(6), 10), // Year
parseInt(date.substring(3,5), 10) - 1, // Month (0-11)
parseInt(date.substring(0,2), 10));
var new_dt = dt.setMilliseconds(dt.getMilliseconds() - numberOfDays*24*60*60*1000);
new_dt = new Date(new_dt);
var changed_date = new_dt.getDate()+"-"+(new_dt.getMonth()+1)+"-"+new_dt.getFullYear();
Hope helps