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 have a form with a simple input type. I'm trying to define a function to check if the date is no more than 6 months older compared to date provided by the input type.
I know i have to convert the String provided by the input in a Date object to make this comparison and then work on get methods of Date object, but i can't figure out how to do this.
Current code:
$scope.compareDates = function(d1) {
d1 = new Date(d1); //convert String into date Object
var d = new Date(); // today date
d.setYear(d.getFullYear());
d.setMonth(d.getMonth() - 6);
if(d1 > d ) {
console.log("ok");
} else {
console.log("error");
}
}
EDIT:
I'm sorry, i forgot to add my input. Here it is:
<input class="form-control" type="text" placeholder="gg/mm/aaaa" ng-model="sStartDate" ng-change="change()">
Angular Controller:
$scope.sStartDate = '';
$scope.change = function(){
var startDt = $scope.sStartDate;
$scope.compareDates(startDt);
}
If I am reading your code correctly, your date format is days/month/year which is not valid format. You need to swap the month and days.
var parts = d1.split(),
dateStr = parts[1] + "/" + parts[0] + "/" parts[2],
d1 = new Date(d1),
d = new Date();
d.setMonth(d.getMonth() - 6);
if(d1 > d ) {
console.log("ok");
} else {
console.log("error");
}
What's about using d.getTime()?
$scope.compareDates = function(d1){
d1 = new Date(d1); //convert String into date Object
var d = new Date(); // today date
d.setMonth(d.getMonth() - 6);
if(d1.getTime() > d.getTime() ) {
console.log("ok");
} else {
console.log("error");
}
}
Regards.
I used momentjs for this in our app. It makes this process very easy and smooth.
// is6MonthsOld will be a boolean value
var is6MonthsOld = moment(d1).isBefore(moment().subtract(6, 'months'));
If you are comparing dates and not time, make sure to reset time in your date object using d1.setHours(0,0,0,0).
When you do new Date(), output is a datetime object, but when you do new Date(2015,6,19), only date is assigned and time is set to 00:00:00.
Following code depicts the same:
function compareDates(d1,d2){
return +d2 > +d1;
}
function compareDatesWithHoursReset(d1,d2){
d1.setHours(0,0,0,0);
d2.setHours(0,0,0,0);
return +d2 > +d1;
}
function main(){
var d1 = new Date();
var d2 = new Date(2015, 6, 19);
d1.setMonth(d1.getMonth() - 6)
console.log(d1);
console.log(d2);
console.log(compareDates(d2,d1))
console.log(compareDatesWithHoursReset(d2,d1))
}
main();
I have a date/time in an input (#myinput) using the following format:
yyyy/mm/dd hh:mm:ss
I need to compare this to todays date, so something like this...
var currentdate = new Date();
if(currentdate < $("#myinput").val()) {
alert("HELLO WORLD");
return false;
}
Any ideas?
I am using moment.js (http://momentjs.com/) for this kind of work.
Would look something like this:
var input = moment($("#myinput").val(), "YYYY/MM/DD HH:mm:ss");
if(input.diff(moment())>0){
...
If i had to use javascript only, i would use a regular expression to parse the date:
var dateString = "2012/12/05 12:00:01";
var regexp = /([0-9]{4})\/([0-9]{2})\/([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/;
var result = regexp.exec(dateString);
var date = new Date();
date.setYear(result[1]);
date.setMonth(result[2]-1);
date.setDate(result[3]);
date.setHours(result[4]);
date.setMinutes(result[5]);
date.setSeconds(result[6]);
if(new Date()<date){
...
You can use the Date.Parse method (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/parse) to compare the date inside your input against the current date or other dates in any kind of correct date format.
Ex:
var testDate = $('#myinput').val();
var d = new Date;
if (Date.parse(d)<Date.parse(testDate)) {
}
else{
}
Here is a fiddle: http://jsfiddle.net/uLybp/3/
use this function
//get full data now
function dateNow(){
var now = new Date(Date.now());
var dd=now.getDay() + "-" + (now.getMonth()+1) + "-" + now.getFullYear()+" ";
dd += now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
return dd;
}
example
var d=dateNow();
console.log(d); // 5-2-2021 1:35:24
Suppose I receive two dates from the datepicker plugin in format DD/MM/YYYY
var date1 = '25/02/1985'; /*february 25th*/
var date2 = '26/02/1985'; /*february 26th*/
/*this dates are results form datepicker*/
if(process(date2) > process(date1)){
alert(date2 + 'is later than ' + date1);
}
What should this function look like?
function process(date){
var date;
// Do something
return date;
}
Split on the "/" and use the Date constructor.
function process(date){
var parts = date.split("/");
return new Date(parts[2], parts[1] - 1, parts[0]);
}
It could be more easier:
var date1 = '25/02/1985'; /*february 25th*/
var date2 = '26/02/1985'; /*february 26th*/
if ($.datepicker.parseDate('dd/mm/yy', date2) > $.datepicker.parseDate('dd/mm/yy', date1)) {
alert(date2 + 'is later than ' + date1);
}
For more details check this out. Thanks.
function process(date){
var parts = date.split("/");
var date = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
return date.getTime();
}