Add days to JavaScript Date
How to add days to current Date
using JavaScript. Does JavaScript have a built in function like .Net's AddDay
?
javascript date datetime time
add a comment |
How to add days to current Date
using JavaScript. Does JavaScript have a built in function like .Net's AddDay
?
javascript date datetime time
add a comment |
How to add days to current Date
using JavaScript. Does JavaScript have a built in function like .Net's AddDay
?
javascript date datetime time
How to add days to current Date
using JavaScript. Does JavaScript have a built in function like .Net's AddDay
?
javascript date datetime time
javascript date datetime time
edited Apr 16 '18 at 9:02
John Slegers
27.5k13146128
27.5k13146128
asked Feb 18 '09 at 23:57
Ashesh
4,0093148
4,0093148
add a comment |
add a comment |
37 Answers
37
active
oldest
votes
1 2
next
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();
alert(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.
14
Simplified:Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
– Duncan
Oct 15 '14 at 17:51
15
@Duncan Are you sure this is the same as the above? This one simply adds 24 hours, but one day is not always 24 hours. I guess the question is how to increment the date part by 1 day, without changing the time part.
– Tamás Bolvári
Dec 19 '15 at 6:41
53
864E5
for some reason I prefer to write24*60*60
in my code :)
– Michal Stefanow
Jan 21 '16 at 20:53
33
Guys, do not use method of adding 864E5 because this does not take daylight saving difference where days can be 23 or 25 hours.
– sbrbot
Jul 25 '16 at 21:44
8
For those of you worried about Daylight Savings -- Don't. These algorithms change the underlying date, not how the date is interpreted. DST is implemented in the getters and setters of the date -- the getters to subtract an hour in the summer, and the setter to add that hour back during the summer to normalize the time. But only when using an absolute hour -- relative hours don't need to be interpreted. This is why date math works. IMHO...
– Gerard ONeill
Nov 22 '16 at 16:53
|
show 9 more comments
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>
Same as this one right?
– bzlm
Oct 30 '13 at 19:26
@bzlm, Yes essentially the same. It just doesn't modify the Date prototype. I also wanted to point out the flaws in the main answer.
– sparebytes
Oct 30 '13 at 19:27
6
@bzlm: Yes, I believe the note should read "this approach fails if the 'from' date is not in the same year or month as the current date". I still worry that users will glance over the answer and not read the warning since it doesn't stand out. Thanks.
– sparebytes
Oct 30 '13 at 19:40
3
I think, even if this work it is not correct. There is no such constructor for Date: var result = new Date(date);, see http://www.w3schools.com/js/js_dates.asp. Even if this usually work, sometimes can lead to wrong results because of conversion to string and vice versa. It should be var result = new Date(date.getTime());
– Marcin
Nov 10 '15 at 10:22
2
@AnkitBalyan, See other answers. It may not work correctly due to Daylights Savings Time
– sparebytes
Jul 31 '17 at 16:49
|
show 13 more comments
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 it's 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.
1
Yeah? But what is this? (ran on March 31st, 2010): today = new Date(); tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); alert(tomorrow.getMonth()); Says "3". alert(tomorrow); is correct... Why???
– d-_-b
Mar 31 '10 at 2:44
9
@sims month is 0 indexed. Month 3 is April
– Joel Coehoorn
Mar 31 '10 at 3:26
5
Why the need to create 2 separate date objects? Why not simply use the same date object:var d = new Date(); d.setDate( d.getDate() + 1 );
?
– Joseph Silber
Mar 25 '12 at 15:03
6
This approach doesn't work across years. If your starting date is from a few years ago,getDate()
returns the day of that year. Then, callingsetDate
sets the day in the current year. So it is NOT a good general solution. @AnthonyWJones's answer actually works correctly.
– Drew Noakes
Oct 14 '13 at 10:55
3
@DrewNoakes—your assertion that it doesn't work across years is wrong. getDate returns the day in the month, not "day of that year". E.g.var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
gives 3 Jan 2017 which crosses 2 years.
– RobG
Dec 6 '16 at 23:09
|
show 2 more comments
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.
9
Note: this resets time to 00:00:00 (can be an issue or not)
– Álvaro González
Feb 20 '13 at 11:45
Doesn't work on the last day of any month, as you say. Makes this unusable on 12 days of the year. Sounds like a nightmare to debug!!!
– Drew Noakes
Oct 14 '13 at 10:59
3
No Drew, it is usable for all days on year. You can put date offset bigger than 31 or month offset bigger than 12 and this function will recalculate it as day in next month or month in next year. So for example: nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+40); is perfectly well code.
– sbrbot
Nov 11 '13 at 7:30
will this work across year boundaries?
– Dom Vinyard
Jun 11 '15 at 10:15
there is getMonth()+22 - what you think will it work!?
– sbrbot
Jun 11 '15 at 11:20
|
show 2 more comments
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.
39
This solution doesn't take daylight savings into account. So, for example, this will return the same date, 23 hours later:new Date(new Date('11/4/2012').getTime() + 86400000)
– Noah Harrison
Mar 20 '12 at 14:55
4
@NoahMiller The problem which you bring up could be a feature not a bug! Adding 24 hours per day is sometimes the right thing to do, with the goal of knowing the resulting time based on DST. The date that your example returns has a time value of 11pm on November 4th which is what 24 hours later is on that particular day. The original poster asked about datetime which would seem to indicate some desire for correct times of the day. This answer is correct if you are in the case when your goal is the time 24 hours later.
– Andy Novocin
Jun 23 '14 at 15:12
2
I agree Noah, var d2 = new Date(d1.valueOf() + 24 * 60 * 60 * 1000) does what it says, adds a full day worth of ticks to a date.
– Corey Alix
Jul 18 '14 at 16:44
6
This is absolutely correct for some cases (for example for 1 day cookies) and a simpler solution than most of the others. I dont get why it has so many downvotes and so few upvotes :/
– Matmarbon
Nov 6 '14 at 12:05
add a comment |
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.
22
No, this should not be marked as the correct answer since this solution assumes that every day has 24*60*60*1000 seconds but it does not (daylight saving)!
– sbrbot
Jan 12 '13 at 9:06
Any evidence about the 'Feb' problem withsetDate()
? Is it this: stackoverflow.com/questions/5497637/…
– nobar
Feb 4 '13 at 3:21
This doesn't work with daylight saving time.
– Aleksey Bykov
Mar 2 '13 at 19:05
8
+1 This SHOULD be marked as the correct answer. I believe that "daylight saving" is about presentation and not about value, which is just the number of milliseconds. From value-point of view - day is CONST number of millisecs, while in terms of presentation it may vary.
– disfated
Mar 17 '15 at 8:17
1
@disfated—this is not the correct answer. The day going out of daylight saving has 25 hours, but this method only adds 24 so the date will be the same. Using 24hrs to represent a day works if UTC methods are used instead, but why bother when using setDate is more convenient? ;-)
– RobG
Dec 6 '16 at 23:13
add a comment |
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.
4
Reading all the answers around until I find this jewel here. Now that makes sense. Amazing that the today/tomorrow thing was copied in almost all the answers, when it does not make sense at all and it is not "for readibility and clarity" as the author says in the most upvoted answer -in the most upvoted comment-, it is confusing and a bad practice and wrong
– Cesc
Aug 8 '14 at 6:01
add a comment |
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/
1
@kpull1 the asker did not restrict the solution domain by asking if a built-in solution exists.
– user2910265
Oct 30 '14 at 16:15
3
Modern note: Moment.js is incredibly heavy to add for such a small purpose. It's several hundred KB, and isn't webpack-friendly out of the box.
– Joshua Comeau
Nov 25 '16 at 13:24
1
Our preferred library is date-fns. Webpack-friendly, fast, and treats Dates as immutable.
– Luke Williams
Jun 6 '17 at 20:59
1
@LukeWilliams never heard of date-fns until now. will check it out. thanks.
– user2910265
Jun 6 '17 at 21:23
1
@JoshuaComeau If you download it from cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js, it takes up 53,248 bytes on disk. I imagine that's the whole ball o' wax, but I don't know. Anyway, whatever. It's not a big deal.
– birdus
Dec 4 '17 at 18:53
|
show 4 more comments
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;
}
5
The .addDays() method does not work for dates that cross daylight saving time boundaries.
– mskfisher
Apr 29 '13 at 0:02
1
This is one of the better answers here because you (correctly) use the number of millis since the epoc to represent dates/times, and add amounts of millis for adjustments... Why then did you not keep this up for "addMonths"!? And why no add year? Did you get bored?
– Robin
Apr 23 '15 at 13:03
Other than months, time periods can be represented by static numbers. But months can be four different lengths. Also, any time period length from Days and higher may have variable length at DST, so you can't use time-based addition anymore without another level of complexity. I added the addYears(), and I fixed addMonths().
– Suamere
Apr 16 '16 at 19:55
add a comment |
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);
Helped me, thank you.
– Alexander Kim
Jan 17 '16 at 12:15
2
Upvote for not requiring an intermediate date variable.
– Jeff Lowery
Jan 4 '17 at 1:15
this is the best answer because it doesn't have mutation
– knocte
Aug 21 '17 at 16:24
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 12:59
add a comment |
The simplest solution.
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
// and then call
var newDate = new Date().addDays(2); //+2 days
console.log(newDate);
// or
var newDate1 = new Date().addDays(-2); //-2 days
console.log(newDate1);
I think this is the best solution. If we're extending the Date class, then it makes better sense that the Date instance is itself updated.
– Porlune
Jun 13 '17 at 8:25
possible duplicate of this answer
– AXL
Jan 9 '18 at 11:20
add a comment |
Late to the party, but if you use there's an excellent plugin called Moment:jQuery
then
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
1
moment does not need jQuery :)
– aikeru
Oct 11 '14 at 3:51
Even better in that case!!
– RemarkLima
Oct 11 '14 at 8:10
1
Yes, after futzing around with Plain ol' JS for too long, I used Moment , and it just works(tm)!
– caseyamcl
Dec 9 '14 at 13:55
Why would you want to use plugin when a few lines of JS will do?
– frenchie
Feb 18 '16 at 21:25
@frenchie because, what starts as a few lines of JS and because clearly your application is manipulating days, dates and time related information, it'll soon be a few 1000 lines of JS, then you'll be asked to localise the app across 12 languages and timezones and you'd wished you had started out with something like moment ;)
– RemarkLima
Mar 5 '17 at 5:08
add a comment |
Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}
6
It does not take into account daylight saving when there's more or less than 86400000 seconds in a day and can result in logical error (program bug) in your code.
– sbrbot
Jan 12 '13 at 9:08
Sometimes that's needed. The eBay API has x-day auctions which are 24-hour based so your item will end at a different time than it goes up if DST status changes mid-auction. In that case you need to use this type of function to avoid logical errors.
– Andy Novocin
Jun 23 '14 at 15:17
add a comment |
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
2
This one makes the most sense to me. It's simple, elegant and doesn't fall pray to issues moving over months/years.
– uadrive
May 7 '15 at 4:17
1
Simplest answer presented. Building on this, the prototype 'addDays' would be the following:Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
– CrazyIvan1974
Jun 3 '15 at 2:11
CrazyIvan1974 works flawlessly.
– adamitj
Jun 19 '17 at 22:27
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:01
add a comment |
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 would link to the ECMAScript docs, but they are released in PDF ;(
– Blake Mills
Sep 28 '12 at 20:37
1
Re "mozilla docs for setDate() don't indicate that it will handle end of month scenarios". The "docs" have been updated so now they do. ;-)
– RobG
Dec 6 '16 at 23:15
add a comment |
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
add a comment |
No, javascript has no a built in function, but
you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
add a comment |
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;
}
this should be marked as the correct answer
– Sérgio S. Filho
Sep 8 '18 at 16:07
add a comment |
I use something like:
new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)
Works with day saving time:
new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
Works with new year:
new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
It can be parametrized:
function DateAdd(source, amount, step) {
var factor = 1;
if (step == "day") factor = 24 * 60 * 60 * 1000;
else if (step == "hour") factor = 60 * 60 * 1000;
...
new Date(source.getTime() + amount * factor);
}
add a comment |
I am using the following solution.
var msInDay = 86400000;
var daysToAdd = 5;
var now = new Date();
var milliseconds = now.getTime();
var newMillisecods = milliseconds + msInDay * daysToAdd;
var newDate = new Date(newMillisecods);
//or now.setTime(newMillisecods);
Date has a constructor that accepts an int. This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object.
What we do here is convert days to milliseconds and add this value to the value provided by getTime. Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method.
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:00
Stephan, does any other library account for that?
– Vakhtang
Aug 24 '17 at 20:12
now.setDate(now.getDate() + days);
automatically handles DST changes. And I have to correct, leap seconds are ignored in JS timestamps.
– Stephan
Aug 25 '17 at 7:57
add a comment |
Edit:
Instead of setTime()
(or setHours()
) you could do it this way:
Date.prototype.addDays= function(d){
this.setDate(this.getDate() + d);
return this;
};
var tomorrow = new Date().addDays(1);
Old:
Instead of using setTime()
you can use setHours()
:
Date.prototype.addDays= function(d){
this.setHours(this.getHours() + d * 24);
return this;
};
var tomorrow = new Date().addDays(1);
See the JSFiddle...
following this logic you could also add one day ;)d.setDate(d.getDate() + 1);
– Rivenfall
Feb 24 '16 at 17:43
so true. edited!
– spaark
Feb 26 '16 at 9:58
add a comment |
Very simple code to add days in date in java script.
var d = new Date();
d.setDate(d.getDate() + prompt('how many days you want to add write here'));
alert(d);
add a comment |
Our team considers date-fns the best library in this space. It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.
const newDate = DateFns.addDays(oldDate, 2);
add a comment |
There's a setDate and a getDate method, which allow you to do something like this :
var newDate = aDate.setDate(aDate.getDate() + numberOfDays);
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. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
(see also this Fiddle)
add a comment |
//the_day is 2013-12-31
var the_day = Date.UTC(2013, 11, 31);
// Now, the_day will be "1388448000000" in UTC+8;
var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
// Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"
I believe this wouldn't work with daylight saving times, leap seconds, or other timezone changes causing a day to not have 86400s.
– Nicolas Cortot
Dec 28 '13 at 16:29
This is the one that is correct. Date.UTC makes the difference. The only thing to that needs caution is that month starts from 0.
– Devid
Jan 24 '17 at 16:03
add a comment |
For those using Angular:
Just do:
$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);
$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);
add a comment |
try this
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
Don't use this, in case of daylight saving setting this doesn't work because day difference is not 24h. I did the same mistake...
– Tobia
Jan 20 '18 at 7:09
add a comment |
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
add a comment |
You can create your custom helper function here
function plusToDate(currentDate, unit, howMuch) {
var config = {
second: 1000, // 1000 miliseconds
minute: 60000,
hour: 3600000,
day: 86400000,
week: 604800000,
month: 2592000000, // Assuming 30 days in a month
year: 31536000000 // Assuming 365 days in year
};
var now = new Date(currentDate);
return new Date(now + config[unit] * howMuch);
}
var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);
By the way, this is generic solution for adding seconds or minutes or days whatever you want.
Even assuming that a day has 86400 seconds can be incorrect, assuming that there are no leap years can lead to serious errors.
– Stephan
Aug 24 '17 at 12:46
...And also in case of daylight saving settings, difference between two day is not always 24h.
– Tobia
Jan 20 '18 at 7:10
add a comment |
function addDays(n){
var t = new Date();
t.setDate(t.getDate() + n);
var month = "0"+(t.getMonth()+1);
var date = "0"+t.getDate();
month = month.slice(-2);
date = date.slice(-2);
var date = date +"/"+month +"/"+t.getFullYear();
alert(date);
}
addDays(5);
add a comment |
1 2
next
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: false,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f563406%2fadd-days-to-javascript-date%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
StackExchange.ready(function () {
$("#show-editor-button input, #show-editor-button button").click(function () {
var showEditor = function() {
$("#show-editor-button").hide();
$("#post-form").removeClass("dno");
StackExchange.editor.finallyInit();
};
var useFancy = $(this).data('confirm-use-fancy');
if(useFancy == 'True') {
var popupTitle = $(this).data('confirm-fancy-title');
var popupBody = $(this).data('confirm-fancy-body');
var popupAccept = $(this).data('confirm-fancy-accept-button');
$(this).loadPopup({
url: '/post/self-answer-popup',
loaded: function(popup) {
var pTitle = $(popup).find('h2');
var pBody = $(popup).find('.popup-body');
var pSubmit = $(popup).find('.popup-submit');
pTitle.text(popupTitle);
pBody.html(popupBody);
pSubmit.val(popupAccept).click(showEditor);
}
})
} else{
var confirmText = $(this).data('confirm-text');
if (confirmText ? confirm(confirmText) : true) {
showEditor();
}
}
});
});
37 Answers
37
active
oldest
votes
37 Answers
37
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
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();
alert(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.
14
Simplified:Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
– Duncan
Oct 15 '14 at 17:51
15
@Duncan Are you sure this is the same as the above? This one simply adds 24 hours, but one day is not always 24 hours. I guess the question is how to increment the date part by 1 day, without changing the time part.
– Tamás Bolvári
Dec 19 '15 at 6:41
53
864E5
for some reason I prefer to write24*60*60
in my code :)
– Michal Stefanow
Jan 21 '16 at 20:53
33
Guys, do not use method of adding 864E5 because this does not take daylight saving difference where days can be 23 or 25 hours.
– sbrbot
Jul 25 '16 at 21:44
8
For those of you worried about Daylight Savings -- Don't. These algorithms change the underlying date, not how the date is interpreted. DST is implemented in the getters and setters of the date -- the getters to subtract an hour in the summer, and the setter to add that hour back during the summer to normalize the time. But only when using an absolute hour -- relative hours don't need to be interpreted. This is why date math works. IMHO...
– Gerard ONeill
Nov 22 '16 at 16:53
|
show 9 more comments
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();
alert(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.
14
Simplified:Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
– Duncan
Oct 15 '14 at 17:51
15
@Duncan Are you sure this is the same as the above? This one simply adds 24 hours, but one day is not always 24 hours. I guess the question is how to increment the date part by 1 day, without changing the time part.
– Tamás Bolvári
Dec 19 '15 at 6:41
53
864E5
for some reason I prefer to write24*60*60
in my code :)
– Michal Stefanow
Jan 21 '16 at 20:53
33
Guys, do not use method of adding 864E5 because this does not take daylight saving difference where days can be 23 or 25 hours.
– sbrbot
Jul 25 '16 at 21:44
8
For those of you worried about Daylight Savings -- Don't. These algorithms change the underlying date, not how the date is interpreted. DST is implemented in the getters and setters of the date -- the getters to subtract an hour in the summer, and the setter to add that hour back during the summer to normalize the time. But only when using an absolute hour -- relative hours don't need to be interpreted. This is why date math works. IMHO...
– Gerard ONeill
Nov 22 '16 at 16:53
|
show 9 more comments
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();
alert(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.
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();
alert(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.
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
alert(date.addDays(5));
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
alert(date.addDays(5));
edited Jun 28 '18 at 3:51
ʇolɐǝz ǝɥʇ qoq
65711228
65711228
answered Feb 19 '09 at 0:10
AnthonyWJones
162k26216286
162k26216286
14
Simplified:Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
– Duncan
Oct 15 '14 at 17:51
15
@Duncan Are you sure this is the same as the above? This one simply adds 24 hours, but one day is not always 24 hours. I guess the question is how to increment the date part by 1 day, without changing the time part.
– Tamás Bolvári
Dec 19 '15 at 6:41
53
864E5
for some reason I prefer to write24*60*60
in my code :)
– Michal Stefanow
Jan 21 '16 at 20:53
33
Guys, do not use method of adding 864E5 because this does not take daylight saving difference where days can be 23 or 25 hours.
– sbrbot
Jul 25 '16 at 21:44
8
For those of you worried about Daylight Savings -- Don't. These algorithms change the underlying date, not how the date is interpreted. DST is implemented in the getters and setters of the date -- the getters to subtract an hour in the summer, and the setter to add that hour back during the summer to normalize the time. But only when using an absolute hour -- relative hours don't need to be interpreted. This is why date math works. IMHO...
– Gerard ONeill
Nov 22 '16 at 16:53
|
show 9 more comments
14
Simplified:Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
– Duncan
Oct 15 '14 at 17:51
15
@Duncan Are you sure this is the same as the above? This one simply adds 24 hours, but one day is not always 24 hours. I guess the question is how to increment the date part by 1 day, without changing the time part.
– Tamás Bolvári
Dec 19 '15 at 6:41
53
864E5
for some reason I prefer to write24*60*60
in my code :)
– Michal Stefanow
Jan 21 '16 at 20:53
33
Guys, do not use method of adding 864E5 because this does not take daylight saving difference where days can be 23 or 25 hours.
– sbrbot
Jul 25 '16 at 21:44
8
For those of you worried about Daylight Savings -- Don't. These algorithms change the underlying date, not how the date is interpreted. DST is implemented in the getters and setters of the date -- the getters to subtract an hour in the summer, and the setter to add that hour back during the summer to normalize the time. But only when using an absolute hour -- relative hours don't need to be interpreted. This is why date math works. IMHO...
– Gerard ONeill
Nov 22 '16 at 16:53
14
14
Simplified:
Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
– Duncan
Oct 15 '14 at 17:51
Simplified:
Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);};
– Duncan
Oct 15 '14 at 17:51
15
15
@Duncan Are you sure this is the same as the above? This one simply adds 24 hours, but one day is not always 24 hours. I guess the question is how to increment the date part by 1 day, without changing the time part.
– Tamás Bolvári
Dec 19 '15 at 6:41
@Duncan Are you sure this is the same as the above? This one simply adds 24 hours, but one day is not always 24 hours. I guess the question is how to increment the date part by 1 day, without changing the time part.
– Tamás Bolvári
Dec 19 '15 at 6:41
53
53
864E5
for some reason I prefer to write 24*60*60
in my code :)– Michal Stefanow
Jan 21 '16 at 20:53
864E5
for some reason I prefer to write 24*60*60
in my code :)– Michal Stefanow
Jan 21 '16 at 20:53
33
33
Guys, do not use method of adding 864E5 because this does not take daylight saving difference where days can be 23 or 25 hours.
– sbrbot
Jul 25 '16 at 21:44
Guys, do not use method of adding 864E5 because this does not take daylight saving difference where days can be 23 or 25 hours.
– sbrbot
Jul 25 '16 at 21:44
8
8
For those of you worried about Daylight Savings -- Don't. These algorithms change the underlying date, not how the date is interpreted. DST is implemented in the getters and setters of the date -- the getters to subtract an hour in the summer, and the setter to add that hour back during the summer to normalize the time. But only when using an absolute hour -- relative hours don't need to be interpreted. This is why date math works. IMHO...
– Gerard ONeill
Nov 22 '16 at 16:53
For those of you worried about Daylight Savings -- Don't. These algorithms change the underlying date, not how the date is interpreted. DST is implemented in the getters and setters of the date -- the getters to subtract an hour in the summer, and the setter to add that hour back during the summer to normalize the time. But only when using an absolute hour -- relative hours don't need to be interpreted. This is why date math works. IMHO...
– Gerard ONeill
Nov 22 '16 at 16:53
|
show 9 more comments
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>
Same as this one right?
– bzlm
Oct 30 '13 at 19:26
@bzlm, Yes essentially the same. It just doesn't modify the Date prototype. I also wanted to point out the flaws in the main answer.
– sparebytes
Oct 30 '13 at 19:27
6
@bzlm: Yes, I believe the note should read "this approach fails if the 'from' date is not in the same year or month as the current date". I still worry that users will glance over the answer and not read the warning since it doesn't stand out. Thanks.
– sparebytes
Oct 30 '13 at 19:40
3
I think, even if this work it is not correct. There is no such constructor for Date: var result = new Date(date);, see http://www.w3schools.com/js/js_dates.asp. Even if this usually work, sometimes can lead to wrong results because of conversion to string and vice versa. It should be var result = new Date(date.getTime());
– Marcin
Nov 10 '15 at 10:22
2
@AnkitBalyan, See other answers. It may not work correctly due to Daylights Savings Time
– sparebytes
Jul 31 '17 at 16:49
|
show 13 more comments
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>
Same as this one right?
– bzlm
Oct 30 '13 at 19:26
@bzlm, Yes essentially the same. It just doesn't modify the Date prototype. I also wanted to point out the flaws in the main answer.
– sparebytes
Oct 30 '13 at 19:27
6
@bzlm: Yes, I believe the note should read "this approach fails if the 'from' date is not in the same year or month as the current date". I still worry that users will glance over the answer and not read the warning since it doesn't stand out. Thanks.
– sparebytes
Oct 30 '13 at 19:40
3
I think, even if this work it is not correct. There is no such constructor for Date: var result = new Date(date);, see http://www.w3schools.com/js/js_dates.asp. Even if this usually work, sometimes can lead to wrong results because of conversion to string and vice versa. It should be var result = new Date(date.getTime());
– Marcin
Nov 10 '15 at 10:22
2
@AnkitBalyan, See other answers. It may not work correctly due to Daylights Savings Time
– sparebytes
Jul 31 '17 at 16:49
|
show 13 more comments
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>
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>
// 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>
// 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>
edited Jul 11 '17 at 20:00
answered Oct 30 '13 at 18:55
sparebytes
7,15421224
7,15421224
Same as this one right?
– bzlm
Oct 30 '13 at 19:26
@bzlm, Yes essentially the same. It just doesn't modify the Date prototype. I also wanted to point out the flaws in the main answer.
– sparebytes
Oct 30 '13 at 19:27
6
@bzlm: Yes, I believe the note should read "this approach fails if the 'from' date is not in the same year or month as the current date". I still worry that users will glance over the answer and not read the warning since it doesn't stand out. Thanks.
– sparebytes
Oct 30 '13 at 19:40
3
I think, even if this work it is not correct. There is no such constructor for Date: var result = new Date(date);, see http://www.w3schools.com/js/js_dates.asp. Even if this usually work, sometimes can lead to wrong results because of conversion to string and vice versa. It should be var result = new Date(date.getTime());
– Marcin
Nov 10 '15 at 10:22
2
@AnkitBalyan, See other answers. It may not work correctly due to Daylights Savings Time
– sparebytes
Jul 31 '17 at 16:49
|
show 13 more comments
Same as this one right?
– bzlm
Oct 30 '13 at 19:26
@bzlm, Yes essentially the same. It just doesn't modify the Date prototype. I also wanted to point out the flaws in the main answer.
– sparebytes
Oct 30 '13 at 19:27
6
@bzlm: Yes, I believe the note should read "this approach fails if the 'from' date is not in the same year or month as the current date". I still worry that users will glance over the answer and not read the warning since it doesn't stand out. Thanks.
– sparebytes
Oct 30 '13 at 19:40
3
I think, even if this work it is not correct. There is no such constructor for Date: var result = new Date(date);, see http://www.w3schools.com/js/js_dates.asp. Even if this usually work, sometimes can lead to wrong results because of conversion to string and vice versa. It should be var result = new Date(date.getTime());
– Marcin
Nov 10 '15 at 10:22
2
@AnkitBalyan, See other answers. It may not work correctly due to Daylights Savings Time
– sparebytes
Jul 31 '17 at 16:49
Same as this one right?
– bzlm
Oct 30 '13 at 19:26
Same as this one right?
– bzlm
Oct 30 '13 at 19:26
@bzlm, Yes essentially the same. It just doesn't modify the Date prototype. I also wanted to point out the flaws in the main answer.
– sparebytes
Oct 30 '13 at 19:27
@bzlm, Yes essentially the same. It just doesn't modify the Date prototype. I also wanted to point out the flaws in the main answer.
– sparebytes
Oct 30 '13 at 19:27
6
6
@bzlm: Yes, I believe the note should read "this approach fails if the 'from' date is not in the same year or month as the current date". I still worry that users will glance over the answer and not read the warning since it doesn't stand out. Thanks.
– sparebytes
Oct 30 '13 at 19:40
@bzlm: Yes, I believe the note should read "this approach fails if the 'from' date is not in the same year or month as the current date". I still worry that users will glance over the answer and not read the warning since it doesn't stand out. Thanks.
– sparebytes
Oct 30 '13 at 19:40
3
3
I think, even if this work it is not correct. There is no such constructor for Date: var result = new Date(date);, see http://www.w3schools.com/js/js_dates.asp. Even if this usually work, sometimes can lead to wrong results because of conversion to string and vice versa. It should be var result = new Date(date.getTime());
– Marcin
Nov 10 '15 at 10:22
I think, even if this work it is not correct. There is no such constructor for Date: var result = new Date(date);, see http://www.w3schools.com/js/js_dates.asp. Even if this usually work, sometimes can lead to wrong results because of conversion to string and vice versa. It should be var result = new Date(date.getTime());
– Marcin
Nov 10 '15 at 10:22
2
2
@AnkitBalyan, See other answers. It may not work correctly due to Daylights Savings Time
– sparebytes
Jul 31 '17 at 16:49
@AnkitBalyan, See other answers. It may not work correctly due to Daylights Savings Time
– sparebytes
Jul 31 '17 at 16:49
|
show 13 more comments
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 it's 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.
1
Yeah? But what is this? (ran on March 31st, 2010): today = new Date(); tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); alert(tomorrow.getMonth()); Says "3". alert(tomorrow); is correct... Why???
– d-_-b
Mar 31 '10 at 2:44
9
@sims month is 0 indexed. Month 3 is April
– Joel Coehoorn
Mar 31 '10 at 3:26
5
Why the need to create 2 separate date objects? Why not simply use the same date object:var d = new Date(); d.setDate( d.getDate() + 1 );
?
– Joseph Silber
Mar 25 '12 at 15:03
6
This approach doesn't work across years. If your starting date is from a few years ago,getDate()
returns the day of that year. Then, callingsetDate
sets the day in the current year. So it is NOT a good general solution. @AnthonyWJones's answer actually works correctly.
– Drew Noakes
Oct 14 '13 at 10:55
3
@DrewNoakes—your assertion that it doesn't work across years is wrong. getDate returns the day in the month, not "day of that year". E.g.var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
gives 3 Jan 2017 which crosses 2 years.
– RobG
Dec 6 '16 at 23:09
|
show 2 more comments
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 it's 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.
1
Yeah? But what is this? (ran on March 31st, 2010): today = new Date(); tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); alert(tomorrow.getMonth()); Says "3". alert(tomorrow); is correct... Why???
– d-_-b
Mar 31 '10 at 2:44
9
@sims month is 0 indexed. Month 3 is April
– Joel Coehoorn
Mar 31 '10 at 3:26
5
Why the need to create 2 separate date objects? Why not simply use the same date object:var d = new Date(); d.setDate( d.getDate() + 1 );
?
– Joseph Silber
Mar 25 '12 at 15:03
6
This approach doesn't work across years. If your starting date is from a few years ago,getDate()
returns the day of that year. Then, callingsetDate
sets the day in the current year. So it is NOT a good general solution. @AnthonyWJones's answer actually works correctly.
– Drew Noakes
Oct 14 '13 at 10:55
3
@DrewNoakes—your assertion that it doesn't work across years is wrong. getDate returns the day in the month, not "day of that year". E.g.var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
gives 3 Jan 2017 which crosses 2 years.
– RobG
Dec 6 '16 at 23:09
|
show 2 more comments
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 it's current value matches the year and month for "today". However, setting to a date number like "32" normally will still work just fine to move it to the next month.
var 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 it's 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.
edited Oct 14 '13 at 15:15
answered Feb 19 '09 at 0:01
Joel Coehoorn
306k95490721
306k95490721
1
Yeah? But what is this? (ran on March 31st, 2010): today = new Date(); tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); alert(tomorrow.getMonth()); Says "3". alert(tomorrow); is correct... Why???
– d-_-b
Mar 31 '10 at 2:44
9
@sims month is 0 indexed. Month 3 is April
– Joel Coehoorn
Mar 31 '10 at 3:26
5
Why the need to create 2 separate date objects? Why not simply use the same date object:var d = new Date(); d.setDate( d.getDate() + 1 );
?
– Joseph Silber
Mar 25 '12 at 15:03
6
This approach doesn't work across years. If your starting date is from a few years ago,getDate()
returns the day of that year. Then, callingsetDate
sets the day in the current year. So it is NOT a good general solution. @AnthonyWJones's answer actually works correctly.
– Drew Noakes
Oct 14 '13 at 10:55
3
@DrewNoakes—your assertion that it doesn't work across years is wrong. getDate returns the day in the month, not "day of that year". E.g.var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
gives 3 Jan 2017 which crosses 2 years.
– RobG
Dec 6 '16 at 23:09
|
show 2 more comments
1
Yeah? But what is this? (ran on March 31st, 2010): today = new Date(); tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); alert(tomorrow.getMonth()); Says "3". alert(tomorrow); is correct... Why???
– d-_-b
Mar 31 '10 at 2:44
9
@sims month is 0 indexed. Month 3 is April
– Joel Coehoorn
Mar 31 '10 at 3:26
5
Why the need to create 2 separate date objects? Why not simply use the same date object:var d = new Date(); d.setDate( d.getDate() + 1 );
?
– Joseph Silber
Mar 25 '12 at 15:03
6
This approach doesn't work across years. If your starting date is from a few years ago,getDate()
returns the day of that year. Then, callingsetDate
sets the day in the current year. So it is NOT a good general solution. @AnthonyWJones's answer actually works correctly.
– Drew Noakes
Oct 14 '13 at 10:55
3
@DrewNoakes—your assertion that it doesn't work across years is wrong. getDate returns the day in the month, not "day of that year". E.g.var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
gives 3 Jan 2017 which crosses 2 years.
– RobG
Dec 6 '16 at 23:09
1
1
Yeah? But what is this? (ran on March 31st, 2010): today = new Date(); tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); alert(tomorrow.getMonth()); Says "3". alert(tomorrow); is correct... Why???
– d-_-b
Mar 31 '10 at 2:44
Yeah? But what is this? (ran on March 31st, 2010): today = new Date(); tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); alert(tomorrow.getMonth()); Says "3". alert(tomorrow); is correct... Why???
– d-_-b
Mar 31 '10 at 2:44
9
9
@sims month is 0 indexed. Month 3 is April
– Joel Coehoorn
Mar 31 '10 at 3:26
@sims month is 0 indexed. Month 3 is April
– Joel Coehoorn
Mar 31 '10 at 3:26
5
5
Why the need to create 2 separate date objects? Why not simply use the same date object:
var d = new Date(); d.setDate( d.getDate() + 1 );
?– Joseph Silber
Mar 25 '12 at 15:03
Why the need to create 2 separate date objects? Why not simply use the same date object:
var d = new Date(); d.setDate( d.getDate() + 1 );
?– Joseph Silber
Mar 25 '12 at 15:03
6
6
This approach doesn't work across years. If your starting date is from a few years ago,
getDate()
returns the day of that year. Then, calling setDate
sets the day in the current year. So it is NOT a good general solution. @AnthonyWJones's answer actually works correctly.– Drew Noakes
Oct 14 '13 at 10:55
This approach doesn't work across years. If your starting date is from a few years ago,
getDate()
returns the day of that year. Then, calling setDate
sets the day in the current year. So it is NOT a good general solution. @AnthonyWJones's answer actually works correctly.– Drew Noakes
Oct 14 '13 at 10:55
3
3
@DrewNoakes—your assertion that it doesn't work across years is wrong. getDate returns the day in the month, not "day of that year". E.g.
var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
gives 3 Jan 2017 which crosses 2 years.– RobG
Dec 6 '16 at 23:09
@DrewNoakes—your assertion that it doesn't work across years is wrong. getDate returns the day in the month, not "day of that year". E.g.
var d = new Date(2015,11,30);d.setDate(d.getDate() + 370)
gives 3 Jan 2017 which crosses 2 years.– RobG
Dec 6 '16 at 23:09
|
show 2 more comments
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.
9
Note: this resets time to 00:00:00 (can be an issue or not)
– Álvaro González
Feb 20 '13 at 11:45
Doesn't work on the last day of any month, as you say. Makes this unusable on 12 days of the year. Sounds like a nightmare to debug!!!
– Drew Noakes
Oct 14 '13 at 10:59
3
No Drew, it is usable for all days on year. You can put date offset bigger than 31 or month offset bigger than 12 and this function will recalculate it as day in next month or month in next year. So for example: nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+40); is perfectly well code.
– sbrbot
Nov 11 '13 at 7:30
will this work across year boundaries?
– Dom Vinyard
Jun 11 '15 at 10:15
there is getMonth()+22 - what you think will it work!?
– sbrbot
Jun 11 '15 at 11:20
|
show 2 more comments
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.
9
Note: this resets time to 00:00:00 (can be an issue or not)
– Álvaro González
Feb 20 '13 at 11:45
Doesn't work on the last day of any month, as you say. Makes this unusable on 12 days of the year. Sounds like a nightmare to debug!!!
– Drew Noakes
Oct 14 '13 at 10:59
3
No Drew, it is usable for all days on year. You can put date offset bigger than 31 or month offset bigger than 12 and this function will recalculate it as day in next month or month in next year. So for example: nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+40); is perfectly well code.
– sbrbot
Nov 11 '13 at 7:30
will this work across year boundaries?
– Dom Vinyard
Jun 11 '15 at 10:15
there is getMonth()+22 - what you think will it work!?
– sbrbot
Jun 11 '15 at 11:20
|
show 2 more comments
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.
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.
edited Nov 23 '18 at 8:25
answered Dec 3 '12 at 23:42
sbrbot
2,92112144
2,92112144
9
Note: this resets time to 00:00:00 (can be an issue or not)
– Álvaro González
Feb 20 '13 at 11:45
Doesn't work on the last day of any month, as you say. Makes this unusable on 12 days of the year. Sounds like a nightmare to debug!!!
– Drew Noakes
Oct 14 '13 at 10:59
3
No Drew, it is usable for all days on year. You can put date offset bigger than 31 or month offset bigger than 12 and this function will recalculate it as day in next month or month in next year. So for example: nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+40); is perfectly well code.
– sbrbot
Nov 11 '13 at 7:30
will this work across year boundaries?
– Dom Vinyard
Jun 11 '15 at 10:15
there is getMonth()+22 - what you think will it work!?
– sbrbot
Jun 11 '15 at 11:20
|
show 2 more comments
9
Note: this resets time to 00:00:00 (can be an issue or not)
– Álvaro González
Feb 20 '13 at 11:45
Doesn't work on the last day of any month, as you say. Makes this unusable on 12 days of the year. Sounds like a nightmare to debug!!!
– Drew Noakes
Oct 14 '13 at 10:59
3
No Drew, it is usable for all days on year. You can put date offset bigger than 31 or month offset bigger than 12 and this function will recalculate it as day in next month or month in next year. So for example: nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+40); is perfectly well code.
– sbrbot
Nov 11 '13 at 7:30
will this work across year boundaries?
– Dom Vinyard
Jun 11 '15 at 10:15
there is getMonth()+22 - what you think will it work!?
– sbrbot
Jun 11 '15 at 11:20
9
9
Note: this resets time to 00:00:00 (can be an issue or not)
– Álvaro González
Feb 20 '13 at 11:45
Note: this resets time to 00:00:00 (can be an issue or not)
– Álvaro González
Feb 20 '13 at 11:45
Doesn't work on the last day of any month, as you say. Makes this unusable on 12 days of the year. Sounds like a nightmare to debug!!!
– Drew Noakes
Oct 14 '13 at 10:59
Doesn't work on the last day of any month, as you say. Makes this unusable on 12 days of the year. Sounds like a nightmare to debug!!!
– Drew Noakes
Oct 14 '13 at 10:59
3
3
No Drew, it is usable for all days on year. You can put date offset bigger than 31 or month offset bigger than 12 and this function will recalculate it as day in next month or month in next year. So for example: nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+40); is perfectly well code.
– sbrbot
Nov 11 '13 at 7:30
No Drew, it is usable for all days on year. You can put date offset bigger than 31 or month offset bigger than 12 and this function will recalculate it as day in next month or month in next year. So for example: nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+40); is perfectly well code.
– sbrbot
Nov 11 '13 at 7:30
will this work across year boundaries?
– Dom Vinyard
Jun 11 '15 at 10:15
will this work across year boundaries?
– Dom Vinyard
Jun 11 '15 at 10:15
there is getMonth()+22 - what you think will it work!?
– sbrbot
Jun 11 '15 at 11:20
there is getMonth()+22 - what you think will it work!?
– sbrbot
Jun 11 '15 at 11:20
|
show 2 more comments
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.
39
This solution doesn't take daylight savings into account. So, for example, this will return the same date, 23 hours later:new Date(new Date('11/4/2012').getTime() + 86400000)
– Noah Harrison
Mar 20 '12 at 14:55
4
@NoahMiller The problem which you bring up could be a feature not a bug! Adding 24 hours per day is sometimes the right thing to do, with the goal of knowing the resulting time based on DST. The date that your example returns has a time value of 11pm on November 4th which is what 24 hours later is on that particular day. The original poster asked about datetime which would seem to indicate some desire for correct times of the day. This answer is correct if you are in the case when your goal is the time 24 hours later.
– Andy Novocin
Jun 23 '14 at 15:12
2
I agree Noah, var d2 = new Date(d1.valueOf() + 24 * 60 * 60 * 1000) does what it says, adds a full day worth of ticks to a date.
– Corey Alix
Jul 18 '14 at 16:44
6
This is absolutely correct for some cases (for example for 1 day cookies) and a simpler solution than most of the others. I dont get why it has so many downvotes and so few upvotes :/
– Matmarbon
Nov 6 '14 at 12:05
add a comment |
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.
39
This solution doesn't take daylight savings into account. So, for example, this will return the same date, 23 hours later:new Date(new Date('11/4/2012').getTime() + 86400000)
– Noah Harrison
Mar 20 '12 at 14:55
4
@NoahMiller The problem which you bring up could be a feature not a bug! Adding 24 hours per day is sometimes the right thing to do, with the goal of knowing the resulting time based on DST. The date that your example returns has a time value of 11pm on November 4th which is what 24 hours later is on that particular day. The original poster asked about datetime which would seem to indicate some desire for correct times of the day. This answer is correct if you are in the case when your goal is the time 24 hours later.
– Andy Novocin
Jun 23 '14 at 15:12
2
I agree Noah, var d2 = new Date(d1.valueOf() + 24 * 60 * 60 * 1000) does what it says, adds a full day worth of ticks to a date.
– Corey Alix
Jul 18 '14 at 16:44
6
This is absolutely correct for some cases (for example for 1 day cookies) and a simpler solution than most of the others. I dont get why it has so many downvotes and so few upvotes :/
– Matmarbon
Nov 6 '14 at 12:05
add a comment |
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.
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.
answered Feb 15 '12 at 3:56
Jason
847176
847176
39
This solution doesn't take daylight savings into account. So, for example, this will return the same date, 23 hours later:new Date(new Date('11/4/2012').getTime() + 86400000)
– Noah Harrison
Mar 20 '12 at 14:55
4
@NoahMiller The problem which you bring up could be a feature not a bug! Adding 24 hours per day is sometimes the right thing to do, with the goal of knowing the resulting time based on DST. The date that your example returns has a time value of 11pm on November 4th which is what 24 hours later is on that particular day. The original poster asked about datetime which would seem to indicate some desire for correct times of the day. This answer is correct if you are in the case when your goal is the time 24 hours later.
– Andy Novocin
Jun 23 '14 at 15:12
2
I agree Noah, var d2 = new Date(d1.valueOf() + 24 * 60 * 60 * 1000) does what it says, adds a full day worth of ticks to a date.
– Corey Alix
Jul 18 '14 at 16:44
6
This is absolutely correct for some cases (for example for 1 day cookies) and a simpler solution than most of the others. I dont get why it has so many downvotes and so few upvotes :/
– Matmarbon
Nov 6 '14 at 12:05
add a comment |
39
This solution doesn't take daylight savings into account. So, for example, this will return the same date, 23 hours later:new Date(new Date('11/4/2012').getTime() + 86400000)
– Noah Harrison
Mar 20 '12 at 14:55
4
@NoahMiller The problem which you bring up could be a feature not a bug! Adding 24 hours per day is sometimes the right thing to do, with the goal of knowing the resulting time based on DST. The date that your example returns has a time value of 11pm on November 4th which is what 24 hours later is on that particular day. The original poster asked about datetime which would seem to indicate some desire for correct times of the day. This answer is correct if you are in the case when your goal is the time 24 hours later.
– Andy Novocin
Jun 23 '14 at 15:12
2
I agree Noah, var d2 = new Date(d1.valueOf() + 24 * 60 * 60 * 1000) does what it says, adds a full day worth of ticks to a date.
– Corey Alix
Jul 18 '14 at 16:44
6
This is absolutely correct for some cases (for example for 1 day cookies) and a simpler solution than most of the others. I dont get why it has so many downvotes and so few upvotes :/
– Matmarbon
Nov 6 '14 at 12:05
39
39
This solution doesn't take daylight savings into account. So, for example, this will return the same date, 23 hours later:
new Date(new Date('11/4/2012').getTime() + 86400000)
– Noah Harrison
Mar 20 '12 at 14:55
This solution doesn't take daylight savings into account. So, for example, this will return the same date, 23 hours later:
new Date(new Date('11/4/2012').getTime() + 86400000)
– Noah Harrison
Mar 20 '12 at 14:55
4
4
@NoahMiller The problem which you bring up could be a feature not a bug! Adding 24 hours per day is sometimes the right thing to do, with the goal of knowing the resulting time based on DST. The date that your example returns has a time value of 11pm on November 4th which is what 24 hours later is on that particular day. The original poster asked about datetime which would seem to indicate some desire for correct times of the day. This answer is correct if you are in the case when your goal is the time 24 hours later.
– Andy Novocin
Jun 23 '14 at 15:12
@NoahMiller The problem which you bring up could be a feature not a bug! Adding 24 hours per day is sometimes the right thing to do, with the goal of knowing the resulting time based on DST. The date that your example returns has a time value of 11pm on November 4th which is what 24 hours later is on that particular day. The original poster asked about datetime which would seem to indicate some desire for correct times of the day. This answer is correct if you are in the case when your goal is the time 24 hours later.
– Andy Novocin
Jun 23 '14 at 15:12
2
2
I agree Noah, var d2 = new Date(d1.valueOf() + 24 * 60 * 60 * 1000) does what it says, adds a full day worth of ticks to a date.
– Corey Alix
Jul 18 '14 at 16:44
I agree Noah, var d2 = new Date(d1.valueOf() + 24 * 60 * 60 * 1000) does what it says, adds a full day worth of ticks to a date.
– Corey Alix
Jul 18 '14 at 16:44
6
6
This is absolutely correct for some cases (for example for 1 day cookies) and a simpler solution than most of the others. I dont get why it has so many downvotes and so few upvotes :/
– Matmarbon
Nov 6 '14 at 12:05
This is absolutely correct for some cases (for example for 1 day cookies) and a simpler solution than most of the others. I dont get why it has so many downvotes and so few upvotes :/
– Matmarbon
Nov 6 '14 at 12:05
add a comment |
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.
22
No, this should not be marked as the correct answer since this solution assumes that every day has 24*60*60*1000 seconds but it does not (daylight saving)!
– sbrbot
Jan 12 '13 at 9:06
Any evidence about the 'Feb' problem withsetDate()
? Is it this: stackoverflow.com/questions/5497637/…
– nobar
Feb 4 '13 at 3:21
This doesn't work with daylight saving time.
– Aleksey Bykov
Mar 2 '13 at 19:05
8
+1 This SHOULD be marked as the correct answer. I believe that "daylight saving" is about presentation and not about value, which is just the number of milliseconds. From value-point of view - day is CONST number of millisecs, while in terms of presentation it may vary.
– disfated
Mar 17 '15 at 8:17
1
@disfated—this is not the correct answer. The day going out of daylight saving has 25 hours, but this method only adds 24 so the date will be the same. Using 24hrs to represent a day works if UTC methods are used instead, but why bother when using setDate is more convenient? ;-)
– RobG
Dec 6 '16 at 23:13
add a comment |
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.
22
No, this should not be marked as the correct answer since this solution assumes that every day has 24*60*60*1000 seconds but it does not (daylight saving)!
– sbrbot
Jan 12 '13 at 9:06
Any evidence about the 'Feb' problem withsetDate()
? Is it this: stackoverflow.com/questions/5497637/…
– nobar
Feb 4 '13 at 3:21
This doesn't work with daylight saving time.
– Aleksey Bykov
Mar 2 '13 at 19:05
8
+1 This SHOULD be marked as the correct answer. I believe that "daylight saving" is about presentation and not about value, which is just the number of milliseconds. From value-point of view - day is CONST number of millisecs, while in terms of presentation it may vary.
– disfated
Mar 17 '15 at 8:17
1
@disfated—this is not the correct answer. The day going out of daylight saving has 25 hours, but this method only adds 24 so the date will be the same. Using 24hrs to represent a day works if UTC methods are used instead, but why bother when using setDate is more convenient? ;-)
– RobG
Dec 6 '16 at 23:13
add a comment |
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.
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.
answered May 2 '12 at 10:01
sufyan.shoaib
791616
791616
22
No, this should not be marked as the correct answer since this solution assumes that every day has 24*60*60*1000 seconds but it does not (daylight saving)!
– sbrbot
Jan 12 '13 at 9:06
Any evidence about the 'Feb' problem withsetDate()
? Is it this: stackoverflow.com/questions/5497637/…
– nobar
Feb 4 '13 at 3:21
This doesn't work with daylight saving time.
– Aleksey Bykov
Mar 2 '13 at 19:05
8
+1 This SHOULD be marked as the correct answer. I believe that "daylight saving" is about presentation and not about value, which is just the number of milliseconds. From value-point of view - day is CONST number of millisecs, while in terms of presentation it may vary.
– disfated
Mar 17 '15 at 8:17
1
@disfated—this is not the correct answer. The day going out of daylight saving has 25 hours, but this method only adds 24 so the date will be the same. Using 24hrs to represent a day works if UTC methods are used instead, but why bother when using setDate is more convenient? ;-)
– RobG
Dec 6 '16 at 23:13
add a comment |
22
No, this should not be marked as the correct answer since this solution assumes that every day has 24*60*60*1000 seconds but it does not (daylight saving)!
– sbrbot
Jan 12 '13 at 9:06
Any evidence about the 'Feb' problem withsetDate()
? Is it this: stackoverflow.com/questions/5497637/…
– nobar
Feb 4 '13 at 3:21
This doesn't work with daylight saving time.
– Aleksey Bykov
Mar 2 '13 at 19:05
8
+1 This SHOULD be marked as the correct answer. I believe that "daylight saving" is about presentation and not about value, which is just the number of milliseconds. From value-point of view - day is CONST number of millisecs, while in terms of presentation it may vary.
– disfated
Mar 17 '15 at 8:17
1
@disfated—this is not the correct answer. The day going out of daylight saving has 25 hours, but this method only adds 24 so the date will be the same. Using 24hrs to represent a day works if UTC methods are used instead, but why bother when using setDate is more convenient? ;-)
– RobG
Dec 6 '16 at 23:13
22
22
No, this should not be marked as the correct answer since this solution assumes that every day has 24*60*60*1000 seconds but it does not (daylight saving)!
– sbrbot
Jan 12 '13 at 9:06
No, this should not be marked as the correct answer since this solution assumes that every day has 24*60*60*1000 seconds but it does not (daylight saving)!
– sbrbot
Jan 12 '13 at 9:06
Any evidence about the 'Feb' problem with
setDate()
? Is it this: stackoverflow.com/questions/5497637/…– nobar
Feb 4 '13 at 3:21
Any evidence about the 'Feb' problem with
setDate()
? Is it this: stackoverflow.com/questions/5497637/…– nobar
Feb 4 '13 at 3:21
This doesn't work with daylight saving time.
– Aleksey Bykov
Mar 2 '13 at 19:05
This doesn't work with daylight saving time.
– Aleksey Bykov
Mar 2 '13 at 19:05
8
8
+1 This SHOULD be marked as the correct answer. I believe that "daylight saving" is about presentation and not about value, which is just the number of milliseconds. From value-point of view - day is CONST number of millisecs, while in terms of presentation it may vary.
– disfated
Mar 17 '15 at 8:17
+1 This SHOULD be marked as the correct answer. I believe that "daylight saving" is about presentation and not about value, which is just the number of milliseconds. From value-point of view - day is CONST number of millisecs, while in terms of presentation it may vary.
– disfated
Mar 17 '15 at 8:17
1
1
@disfated—this is not the correct answer. The day going out of daylight saving has 25 hours, but this method only adds 24 so the date will be the same. Using 24hrs to represent a day works if UTC methods are used instead, but why bother when using setDate is more convenient? ;-)
– RobG
Dec 6 '16 at 23:13
@disfated—this is not the correct answer. The day going out of daylight saving has 25 hours, but this method only adds 24 so the date will be the same. Using 24hrs to represent a day works if UTC methods are used instead, but why bother when using setDate is more convenient? ;-)
– RobG
Dec 6 '16 at 23:13
add a comment |
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.
4
Reading all the answers around until I find this jewel here. Now that makes sense. Amazing that the today/tomorrow thing was copied in almost all the answers, when it does not make sense at all and it is not "for readibility and clarity" as the author says in the most upvoted answer -in the most upvoted comment-, it is confusing and a bad practice and wrong
– Cesc
Aug 8 '14 at 6:01
add a comment |
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.
4
Reading all the answers around until I find this jewel here. Now that makes sense. Amazing that the today/tomorrow thing was copied in almost all the answers, when it does not make sense at all and it is not "for readibility and clarity" as the author says in the most upvoted answer -in the most upvoted comment-, it is confusing and a bad practice and wrong
– Cesc
Aug 8 '14 at 6:01
add a comment |
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.
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.
edited Apr 10 '16 at 18:31
xiº
2,71931334
2,71931334
answered Feb 14 '13 at 4:15
Rumpleteaser
2,20243148
2,20243148
4
Reading all the answers around until I find this jewel here. Now that makes sense. Amazing that the today/tomorrow thing was copied in almost all the answers, when it does not make sense at all and it is not "for readibility and clarity" as the author says in the most upvoted answer -in the most upvoted comment-, it is confusing and a bad practice and wrong
– Cesc
Aug 8 '14 at 6:01
add a comment |
4
Reading all the answers around until I find this jewel here. Now that makes sense. Amazing that the today/tomorrow thing was copied in almost all the answers, when it does not make sense at all and it is not "for readibility and clarity" as the author says in the most upvoted answer -in the most upvoted comment-, it is confusing and a bad practice and wrong
– Cesc
Aug 8 '14 at 6:01
4
4
Reading all the answers around until I find this jewel here. Now that makes sense. Amazing that the today/tomorrow thing was copied in almost all the answers, when it does not make sense at all and it is not "for readibility and clarity" as the author says in the most upvoted answer -in the most upvoted comment-, it is confusing and a bad practice and wrong
– Cesc
Aug 8 '14 at 6:01
Reading all the answers around until I find this jewel here. Now that makes sense. Amazing that the today/tomorrow thing was copied in almost all the answers, when it does not make sense at all and it is not "for readibility and clarity" as the author says in the most upvoted answer -in the most upvoted comment-, it is confusing and a bad practice and wrong
– Cesc
Aug 8 '14 at 6:01
add a comment |
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/
1
@kpull1 the asker did not restrict the solution domain by asking if a built-in solution exists.
– user2910265
Oct 30 '14 at 16:15
3
Modern note: Moment.js is incredibly heavy to add for such a small purpose. It's several hundred KB, and isn't webpack-friendly out of the box.
– Joshua Comeau
Nov 25 '16 at 13:24
1
Our preferred library is date-fns. Webpack-friendly, fast, and treats Dates as immutable.
– Luke Williams
Jun 6 '17 at 20:59
1
@LukeWilliams never heard of date-fns until now. will check it out. thanks.
– user2910265
Jun 6 '17 at 21:23
1
@JoshuaComeau If you download it from cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js, it takes up 53,248 bytes on disk. I imagine that's the whole ball o' wax, but I don't know. Anyway, whatever. It's not a big deal.
– birdus
Dec 4 '17 at 18:53
|
show 4 more comments
If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:
var nextWeek = moment().add(7, 'days');
alert(nextWeek);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
Reference: http://momentjs.com/docs/#/manipulating/add/
1
@kpull1 the asker did not restrict the solution domain by asking if a built-in solution exists.
– user2910265
Oct 30 '14 at 16:15
3
Modern note: Moment.js is incredibly heavy to add for such a small purpose. It's several hundred KB, and isn't webpack-friendly out of the box.
– Joshua Comeau
Nov 25 '16 at 13:24
1
Our preferred library is date-fns. Webpack-friendly, fast, and treats Dates as immutable.
– Luke Williams
Jun 6 '17 at 20:59
1
@LukeWilliams never heard of date-fns until now. will check it out. thanks.
– user2910265
Jun 6 '17 at 21:23
1
@JoshuaComeau If you download it from cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js, it takes up 53,248 bytes on disk. I imagine that's the whole ball o' wax, but I don't know. Anyway, whatever. It's not a big deal.
– birdus
Dec 4 '17 at 18:53
|
show 4 more comments
If you can, use moment.js. JavaScript doesn't have very good native date/time methods. The following is an example Moment's syntax:
var nextWeek = moment().add(7, 'days');
alert(nextWeek);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
Reference: http://momentjs.com/docs/#/manipulating/add/
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/
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>
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>
edited Feb 1 '17 at 19:29
Ruslan López
2,81811326
2,81811326
answered Dec 22 '13 at 4:46
user2910265
641612
641612
1
@kpull1 the asker did not restrict the solution domain by asking if a built-in solution exists.
– user2910265
Oct 30 '14 at 16:15
3
Modern note: Moment.js is incredibly heavy to add for such a small purpose. It's several hundred KB, and isn't webpack-friendly out of the box.
– Joshua Comeau
Nov 25 '16 at 13:24
1
Our preferred library is date-fns. Webpack-friendly, fast, and treats Dates as immutable.
– Luke Williams
Jun 6 '17 at 20:59
1
@LukeWilliams never heard of date-fns until now. will check it out. thanks.
– user2910265
Jun 6 '17 at 21:23
1
@JoshuaComeau If you download it from cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js, it takes up 53,248 bytes on disk. I imagine that's the whole ball o' wax, but I don't know. Anyway, whatever. It's not a big deal.
– birdus
Dec 4 '17 at 18:53
|
show 4 more comments
1
@kpull1 the asker did not restrict the solution domain by asking if a built-in solution exists.
– user2910265
Oct 30 '14 at 16:15
3
Modern note: Moment.js is incredibly heavy to add for such a small purpose. It's several hundred KB, and isn't webpack-friendly out of the box.
– Joshua Comeau
Nov 25 '16 at 13:24
1
Our preferred library is date-fns. Webpack-friendly, fast, and treats Dates as immutable.
– Luke Williams
Jun 6 '17 at 20:59
1
@LukeWilliams never heard of date-fns until now. will check it out. thanks.
– user2910265
Jun 6 '17 at 21:23
1
@JoshuaComeau If you download it from cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js, it takes up 53,248 bytes on disk. I imagine that's the whole ball o' wax, but I don't know. Anyway, whatever. It's not a big deal.
– birdus
Dec 4 '17 at 18:53
1
1
@kpull1 the asker did not restrict the solution domain by asking if a built-in solution exists.
– user2910265
Oct 30 '14 at 16:15
@kpull1 the asker did not restrict the solution domain by asking if a built-in solution exists.
– user2910265
Oct 30 '14 at 16:15
3
3
Modern note: Moment.js is incredibly heavy to add for such a small purpose. It's several hundred KB, and isn't webpack-friendly out of the box.
– Joshua Comeau
Nov 25 '16 at 13:24
Modern note: Moment.js is incredibly heavy to add for such a small purpose. It's several hundred KB, and isn't webpack-friendly out of the box.
– Joshua Comeau
Nov 25 '16 at 13:24
1
1
Our preferred library is date-fns. Webpack-friendly, fast, and treats Dates as immutable.
– Luke Williams
Jun 6 '17 at 20:59
Our preferred library is date-fns. Webpack-friendly, fast, and treats Dates as immutable.
– Luke Williams
Jun 6 '17 at 20:59
1
1
@LukeWilliams never heard of date-fns until now. will check it out. thanks.
– user2910265
Jun 6 '17 at 21:23
@LukeWilliams never heard of date-fns until now. will check it out. thanks.
– user2910265
Jun 6 '17 at 21:23
1
1
@JoshuaComeau If you download it from cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js, it takes up 53,248 bytes on disk. I imagine that's the whole ball o' wax, but I don't know. Anyway, whatever. It's not a big deal.
– birdus
Dec 4 '17 at 18:53
@JoshuaComeau If you download it from cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js, it takes up 53,248 bytes on disk. I imagine that's the whole ball o' wax, but I don't know. Anyway, whatever. It's not a big deal.
– birdus
Dec 4 '17 at 18:53
|
show 4 more comments
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;
}
5
The .addDays() method does not work for dates that cross daylight saving time boundaries.
– mskfisher
Apr 29 '13 at 0:02
1
This is one of the better answers here because you (correctly) use the number of millis since the epoc to represent dates/times, and add amounts of millis for adjustments... Why then did you not keep this up for "addMonths"!? And why no add year? Did you get bored?
– Robin
Apr 23 '15 at 13:03
Other than months, time periods can be represented by static numbers. But months can be four different lengths. Also, any time period length from Days and higher may have variable length at DST, so you can't use time-based addition anymore without another level of complexity. I added the addYears(), and I fixed addMonths().
– Suamere
Apr 16 '16 at 19:55
add a comment |
I created these extensions last night:
you can pass either positive or negative values;
example:
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);
Date.prototype.addDays = function (num) {
var value = this.valueOf();
value += 86400000 * num;
return new Date(value);
}
Date.prototype.addSeconds = function (num) {
var value = this.valueOf();
value += 1000 * num;
return new Date(value);
}
Date.prototype.addMinutes = function (num) {
var value = this.valueOf();
value += 60000 * num;
return new Date(value);
}
Date.prototype.addHours = function (num) {
var value = this.valueOf();
value += 3600000 * num;
return new Date(value);
}
Date.prototype.addMonths = function (num) {
var value = new Date(this.valueOf());
var mo = this.getMonth();
var yr = this.getYear();
mo = (mo + num) % 12;
if (0 > mo) {
yr += (this.getMonth() + num - mo - 12) / 12;
mo += 12;
}
else
yr += ((this.getMonth() + num - mo) / 12);
value.setMonth(mo);
value.setYear(yr);
return value;
}
5
The .addDays() method does not work for dates that cross daylight saving time boundaries.
– mskfisher
Apr 29 '13 at 0:02
1
This is one of the better answers here because you (correctly) use the number of millis since the epoc to represent dates/times, and add amounts of millis for adjustments... Why then did you not keep this up for "addMonths"!? And why no add year? Did you get bored?
– Robin
Apr 23 '15 at 13:03
Other than months, time periods can be represented by static numbers. But months can be four different lengths. Also, any time period length from Days and higher may have variable length at DST, so you can't use time-based addition anymore without another level of complexity. I added the addYears(), and I fixed addMonths().
– Suamere
Apr 16 '16 at 19:55
add a comment |
I created these extensions last night:
you can pass either positive or negative values;
example:
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);
Date.prototype.addDays = function (num) {
var value = this.valueOf();
value += 86400000 * num;
return new Date(value);
}
Date.prototype.addSeconds = function (num) {
var value = this.valueOf();
value += 1000 * num;
return new Date(value);
}
Date.prototype.addMinutes = function (num) {
var value = this.valueOf();
value += 60000 * num;
return new Date(value);
}
Date.prototype.addHours = function (num) {
var value = this.valueOf();
value += 3600000 * num;
return new Date(value);
}
Date.prototype.addMonths = function (num) {
var value = new Date(this.valueOf());
var mo = this.getMonth();
var yr = this.getYear();
mo = (mo + num) % 12;
if (0 > mo) {
yr += (this.getMonth() + num - mo - 12) / 12;
mo += 12;
}
else
yr += ((this.getMonth() + num - mo) / 12);
value.setMonth(mo);
value.setYear(yr);
return value;
}
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;
}
edited Apr 5 '13 at 3:36
user2022859
answered Apr 5 '13 at 3:15
mark.nino.chua
20524
20524
5
The .addDays() method does not work for dates that cross daylight saving time boundaries.
– mskfisher
Apr 29 '13 at 0:02
1
This is one of the better answers here because you (correctly) use the number of millis since the epoc to represent dates/times, and add amounts of millis for adjustments... Why then did you not keep this up for "addMonths"!? And why no add year? Did you get bored?
– Robin
Apr 23 '15 at 13:03
Other than months, time periods can be represented by static numbers. But months can be four different lengths. Also, any time period length from Days and higher may have variable length at DST, so you can't use time-based addition anymore without another level of complexity. I added the addYears(), and I fixed addMonths().
– Suamere
Apr 16 '16 at 19:55
add a comment |
5
The .addDays() method does not work for dates that cross daylight saving time boundaries.
– mskfisher
Apr 29 '13 at 0:02
1
This is one of the better answers here because you (correctly) use the number of millis since the epoc to represent dates/times, and add amounts of millis for adjustments... Why then did you not keep this up for "addMonths"!? And why no add year? Did you get bored?
– Robin
Apr 23 '15 at 13:03
Other than months, time periods can be represented by static numbers. But months can be four different lengths. Also, any time period length from Days and higher may have variable length at DST, so you can't use time-based addition anymore without another level of complexity. I added the addYears(), and I fixed addMonths().
– Suamere
Apr 16 '16 at 19:55
5
5
The .addDays() method does not work for dates that cross daylight saving time boundaries.
– mskfisher
Apr 29 '13 at 0:02
The .addDays() method does not work for dates that cross daylight saving time boundaries.
– mskfisher
Apr 29 '13 at 0:02
1
1
This is one of the better answers here because you (correctly) use the number of millis since the epoc to represent dates/times, and add amounts of millis for adjustments... Why then did you not keep this up for "addMonths"!? And why no add year? Did you get bored?
– Robin
Apr 23 '15 at 13:03
This is one of the better answers here because you (correctly) use the number of millis since the epoc to represent dates/times, and add amounts of millis for adjustments... Why then did you not keep this up for "addMonths"!? And why no add year? Did you get bored?
– Robin
Apr 23 '15 at 13:03
Other than months, time periods can be represented by static numbers. But months can be four different lengths. Also, any time period length from Days and higher may have variable length at DST, so you can't use time-based addition anymore without another level of complexity. I added the addYears(), and I fixed addMonths().
– Suamere
Apr 16 '16 at 19:55
Other than months, time periods can be represented by static numbers. But months can be four different lengths. Also, any time period length from Days and higher may have variable length at DST, so you can't use time-based addition anymore without another level of complexity. I added the addYears(), and I fixed addMonths().
– Suamere
Apr 16 '16 at 19:55
add a comment |
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);
Helped me, thank you.
– Alexander Kim
Jan 17 '16 at 12:15
2
Upvote for not requiring an intermediate date variable.
– Jeff Lowery
Jan 4 '17 at 1:15
this is the best answer because it doesn't have mutation
– knocte
Aug 21 '17 at 16:24
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 12:59
add a comment |
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);
Helped me, thank you.
– Alexander Kim
Jan 17 '16 at 12:15
2
Upvote for not requiring an intermediate date variable.
– Jeff Lowery
Jan 4 '17 at 1:15
this is the best answer because it doesn't have mutation
– knocte
Aug 21 '17 at 16:24
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 12:59
add a comment |
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);
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);
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);
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);
answered Dec 1 '15 at 10:03
Serge
3,08233879
3,08233879
Helped me, thank you.
– Alexander Kim
Jan 17 '16 at 12:15
2
Upvote for not requiring an intermediate date variable.
– Jeff Lowery
Jan 4 '17 at 1:15
this is the best answer because it doesn't have mutation
– knocte
Aug 21 '17 at 16:24
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 12:59
add a comment |
Helped me, thank you.
– Alexander Kim
Jan 17 '16 at 12:15
2
Upvote for not requiring an intermediate date variable.
– Jeff Lowery
Jan 4 '17 at 1:15
this is the best answer because it doesn't have mutation
– knocte
Aug 21 '17 at 16:24
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 12:59
Helped me, thank you.
– Alexander Kim
Jan 17 '16 at 12:15
Helped me, thank you.
– Alexander Kim
Jan 17 '16 at 12:15
2
2
Upvote for not requiring an intermediate date variable.
– Jeff Lowery
Jan 4 '17 at 1:15
Upvote for not requiring an intermediate date variable.
– Jeff Lowery
Jan 4 '17 at 1:15
this is the best answer because it doesn't have mutation
– knocte
Aug 21 '17 at 16:24
this is the best answer because it doesn't have mutation
– knocte
Aug 21 '17 at 16:24
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 12:59
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 12:59
add a comment |
The simplest solution.
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
// and then call
var newDate = new Date().addDays(2); //+2 days
console.log(newDate);
// or
var newDate1 = new Date().addDays(-2); //-2 days
console.log(newDate1);
I think this is the best solution. If we're extending the Date class, then it makes better sense that the Date instance is itself updated.
– Porlune
Jun 13 '17 at 8:25
possible duplicate of this answer
– AXL
Jan 9 '18 at 11:20
add a comment |
The simplest solution.
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
// and then call
var newDate = new Date().addDays(2); //+2 days
console.log(newDate);
// or
var newDate1 = new Date().addDays(-2); //-2 days
console.log(newDate1);
I think this is the best solution. If we're extending the Date class, then it makes better sense that the Date instance is itself updated.
– Porlune
Jun 13 '17 at 8:25
possible duplicate of this answer
– AXL
Jan 9 '18 at 11:20
add a comment |
The simplest solution.
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
// and then call
var newDate = new Date().addDays(2); //+2 days
console.log(newDate);
// or
var newDate1 = new Date().addDays(-2); //-2 days
console.log(newDate1);
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);
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);
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);
edited Feb 1 '17 at 19:00
Ruslan López
2,81811326
2,81811326
answered Jun 17 '16 at 11:29
ampachts
10915
10915
I think this is the best solution. If we're extending the Date class, then it makes better sense that the Date instance is itself updated.
– Porlune
Jun 13 '17 at 8:25
possible duplicate of this answer
– AXL
Jan 9 '18 at 11:20
add a comment |
I think this is the best solution. If we're extending the Date class, then it makes better sense that the Date instance is itself updated.
– Porlune
Jun 13 '17 at 8:25
possible duplicate of this answer
– AXL
Jan 9 '18 at 11:20
I think this is the best solution. If we're extending the Date class, then it makes better sense that the Date instance is itself updated.
– Porlune
Jun 13 '17 at 8:25
I think this is the best solution. If we're extending the Date class, then it makes better sense that the Date instance is itself updated.
– Porlune
Jun 13 '17 at 8:25
possible duplicate of this answer
– AXL
Jan 9 '18 at 11:20
possible duplicate of this answer
– AXL
Jan 9 '18 at 11:20
add a comment |
Late to the party, but if you use there's an excellent plugin called Moment:jQuery
then
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
1
moment does not need jQuery :)
– aikeru
Oct 11 '14 at 3:51
Even better in that case!!
– RemarkLima
Oct 11 '14 at 8:10
1
Yes, after futzing around with Plain ol' JS for too long, I used Moment , and it just works(tm)!
– caseyamcl
Dec 9 '14 at 13:55
Why would you want to use plugin when a few lines of JS will do?
– frenchie
Feb 18 '16 at 21:25
@frenchie because, what starts as a few lines of JS and because clearly your application is manipulating days, dates and time related information, it'll soon be a few 1000 lines of JS, then you'll be asked to localise the app across 12 languages and timezones and you'd wished you had started out with something like moment ;)
– RemarkLima
Mar 5 '17 at 5:08
add a comment |
Late to the party, but if you use there's an excellent plugin called Moment:jQuery
then
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
1
moment does not need jQuery :)
– aikeru
Oct 11 '14 at 3:51
Even better in that case!!
– RemarkLima
Oct 11 '14 at 8:10
1
Yes, after futzing around with Plain ol' JS for too long, I used Moment , and it just works(tm)!
– caseyamcl
Dec 9 '14 at 13:55
Why would you want to use plugin when a few lines of JS will do?
– frenchie
Feb 18 '16 at 21:25
@frenchie because, what starts as a few lines of JS and because clearly your application is manipulating days, dates and time related information, it'll soon be a few 1000 lines of JS, then you'll be asked to localise the app across 12 languages and timezones and you'd wished you had started out with something like moment ;)
– RemarkLima
Mar 5 '17 at 5:08
add a comment |
Late to the party, but if you use there's an excellent plugin called Moment:jQuery
then
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
Late to the party, but if you use there's an excellent plugin called Moment:jQuery
then
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
edited Oct 11 '14 at 8:12
answered Oct 3 '14 at 14:54
RemarkLima
7,57762637
7,57762637
1
moment does not need jQuery :)
– aikeru
Oct 11 '14 at 3:51
Even better in that case!!
– RemarkLima
Oct 11 '14 at 8:10
1
Yes, after futzing around with Plain ol' JS for too long, I used Moment , and it just works(tm)!
– caseyamcl
Dec 9 '14 at 13:55
Why would you want to use plugin when a few lines of JS will do?
– frenchie
Feb 18 '16 at 21:25
@frenchie because, what starts as a few lines of JS and because clearly your application is manipulating days, dates and time related information, it'll soon be a few 1000 lines of JS, then you'll be asked to localise the app across 12 languages and timezones and you'd wished you had started out with something like moment ;)
– RemarkLima
Mar 5 '17 at 5:08
add a comment |
1
moment does not need jQuery :)
– aikeru
Oct 11 '14 at 3:51
Even better in that case!!
– RemarkLima
Oct 11 '14 at 8:10
1
Yes, after futzing around with Plain ol' JS for too long, I used Moment , and it just works(tm)!
– caseyamcl
Dec 9 '14 at 13:55
Why would you want to use plugin when a few lines of JS will do?
– frenchie
Feb 18 '16 at 21:25
@frenchie because, what starts as a few lines of JS and because clearly your application is manipulating days, dates and time related information, it'll soon be a few 1000 lines of JS, then you'll be asked to localise the app across 12 languages and timezones and you'd wished you had started out with something like moment ;)
– RemarkLima
Mar 5 '17 at 5:08
1
1
moment does not need jQuery :)
– aikeru
Oct 11 '14 at 3:51
moment does not need jQuery :)
– aikeru
Oct 11 '14 at 3:51
Even better in that case!!
– RemarkLima
Oct 11 '14 at 8:10
Even better in that case!!
– RemarkLima
Oct 11 '14 at 8:10
1
1
Yes, after futzing around with Plain ol' JS for too long, I used Moment , and it just works(tm)!
– caseyamcl
Dec 9 '14 at 13:55
Yes, after futzing around with Plain ol' JS for too long, I used Moment , and it just works(tm)!
– caseyamcl
Dec 9 '14 at 13:55
Why would you want to use plugin when a few lines of JS will do?
– frenchie
Feb 18 '16 at 21:25
Why would you want to use plugin when a few lines of JS will do?
– frenchie
Feb 18 '16 at 21:25
@frenchie because, what starts as a few lines of JS and because clearly your application is manipulating days, dates and time related information, it'll soon be a few 1000 lines of JS, then you'll be asked to localise the app across 12 languages and timezones and you'd wished you had started out with something like moment ;)
– RemarkLima
Mar 5 '17 at 5:08
@frenchie because, what starts as a few lines of JS and because clearly your application is manipulating days, dates and time related information, it'll soon be a few 1000 lines of JS, then you'll be asked to localise the app across 12 languages and timezones and you'd wished you had started out with something like moment ;)
– RemarkLima
Mar 5 '17 at 5:08
add a comment |
Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}
6
It does not take into account daylight saving when there's more or less than 86400000 seconds in a day and can result in logical error (program bug) in your code.
– sbrbot
Jan 12 '13 at 9:08
Sometimes that's needed. The eBay API has x-day auctions which are 24-hour based so your item will end at a different time than it goes up if DST status changes mid-auction. In that case you need to use this type of function to avoid logical errors.
– Andy Novocin
Jun 23 '14 at 15:17
add a comment |
Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}
6
It does not take into account daylight saving when there's more or less than 86400000 seconds in a day and can result in logical error (program bug) in your code.
– sbrbot
Jan 12 '13 at 9:08
Sometimes that's needed. The eBay API has x-day auctions which are 24-hour based so your item will end at a different time than it goes up if DST status changes mid-auction. In that case you need to use this type of function to avoid logical errors.
– Andy Novocin
Jun 23 '14 at 15:17
add a comment |
Thanks Jason for your answer that works as expected, here is a mix from your code and the handy format of AnthonyWJones :
Date.prototype.addDays = function(days){
var ms = new Date().getTime() + (86400000 * days);
var added = new Date(ms);
return added;
}
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;
}
edited Sep 4 '12 at 19:20
answered Sep 4 '12 at 16:16
Olivier
1,1911213
1,1911213
6
It does not take into account daylight saving when there's more or less than 86400000 seconds in a day and can result in logical error (program bug) in your code.
– sbrbot
Jan 12 '13 at 9:08
Sometimes that's needed. The eBay API has x-day auctions which are 24-hour based so your item will end at a different time than it goes up if DST status changes mid-auction. In that case you need to use this type of function to avoid logical errors.
– Andy Novocin
Jun 23 '14 at 15:17
add a comment |
6
It does not take into account daylight saving when there's more or less than 86400000 seconds in a day and can result in logical error (program bug) in your code.
– sbrbot
Jan 12 '13 at 9:08
Sometimes that's needed. The eBay API has x-day auctions which are 24-hour based so your item will end at a different time than it goes up if DST status changes mid-auction. In that case you need to use this type of function to avoid logical errors.
– Andy Novocin
Jun 23 '14 at 15:17
6
6
It does not take into account daylight saving when there's more or less than 86400000 seconds in a day and can result in logical error (program bug) in your code.
– sbrbot
Jan 12 '13 at 9:08
It does not take into account daylight saving when there's more or less than 86400000 seconds in a day and can result in logical error (program bug) in your code.
– sbrbot
Jan 12 '13 at 9:08
Sometimes that's needed. The eBay API has x-day auctions which are 24-hour based so your item will end at a different time than it goes up if DST status changes mid-auction. In that case you need to use this type of function to avoid logical errors.
– Andy Novocin
Jun 23 '14 at 15:17
Sometimes that's needed. The eBay API has x-day auctions which are 24-hour based so your item will end at a different time than it goes up if DST status changes mid-auction. In that case you need to use this type of function to avoid logical errors.
– Andy Novocin
Jun 23 '14 at 15:17
add a comment |
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
2
This one makes the most sense to me. It's simple, elegant and doesn't fall pray to issues moving over months/years.
– uadrive
May 7 '15 at 4:17
1
Simplest answer presented. Building on this, the prototype 'addDays' would be the following:Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
– CrazyIvan1974
Jun 3 '15 at 2:11
CrazyIvan1974 works flawlessly.
– adamitj
Jun 19 '17 at 22:27
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:01
add a comment |
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
2
This one makes the most sense to me. It's simple, elegant and doesn't fall pray to issues moving over months/years.
– uadrive
May 7 '15 at 4:17
1
Simplest answer presented. Building on this, the prototype 'addDays' would be the following:Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
– CrazyIvan1974
Jun 3 '15 at 2:11
CrazyIvan1974 works flawlessly.
– adamitj
Jun 19 '17 at 22:27
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:01
add a comment |
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
answered Dec 12 '14 at 22:10
Todd
4,47322138
4,47322138
2
This one makes the most sense to me. It's simple, elegant and doesn't fall pray to issues moving over months/years.
– uadrive
May 7 '15 at 4:17
1
Simplest answer presented. Building on this, the prototype 'addDays' would be the following:Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
– CrazyIvan1974
Jun 3 '15 at 2:11
CrazyIvan1974 works flawlessly.
– adamitj
Jun 19 '17 at 22:27
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:01
add a comment |
2
This one makes the most sense to me. It's simple, elegant and doesn't fall pray to issues moving over months/years.
– uadrive
May 7 '15 at 4:17
1
Simplest answer presented. Building on this, the prototype 'addDays' would be the following:Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
– CrazyIvan1974
Jun 3 '15 at 2:11
CrazyIvan1974 works flawlessly.
– adamitj
Jun 19 '17 at 22:27
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:01
2
2
This one makes the most sense to me. It's simple, elegant and doesn't fall pray to issues moving over months/years.
– uadrive
May 7 '15 at 4:17
This one makes the most sense to me. It's simple, elegant and doesn't fall pray to issues moving over months/years.
– uadrive
May 7 '15 at 4:17
1
1
Simplest answer presented. Building on this, the prototype 'addDays' would be the following:
Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
– CrazyIvan1974
Jun 3 '15 at 2:11
Simplest answer presented. Building on this, the prototype 'addDays' would be the following:
Date.prototype.addDays = function(days) {return new Date(this.getTime() + (864e5 * days));};
– CrazyIvan1974
Jun 3 '15 at 2:11
CrazyIvan1974 works flawlessly.
– adamitj
Jun 19 '17 at 22:27
CrazyIvan1974 works flawlessly.
– adamitj
Jun 19 '17 at 22:27
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:01
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:01
add a comment |
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 would link to the ECMAScript docs, but they are released in PDF ;(
– Blake Mills
Sep 28 '12 at 20:37
1
Re "mozilla docs for setDate() don't indicate that it will handle end of month scenarios". The "docs" have been updated so now they do. ;-)
– RobG
Dec 6 '16 at 23:15
add a comment |
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 would link to the ECMAScript docs, but they are released in PDF ;(
– Blake Mills
Sep 28 '12 at 20:37
1
Re "mozilla docs for setDate() don't indicate that it will handle end of month scenarios". The "docs" have been updated so now they do. ;-)
– RobG
Dec 6 '16 at 23:15
add a comment |
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.
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.
answered Sep 28 '12 at 20:11
Blake Mills
5292614
5292614
I would link to the ECMAScript docs, but they are released in PDF ;(
– Blake Mills
Sep 28 '12 at 20:37
1
Re "mozilla docs for setDate() don't indicate that it will handle end of month scenarios". The "docs" have been updated so now they do. ;-)
– RobG
Dec 6 '16 at 23:15
add a comment |
I would link to the ECMAScript docs, but they are released in PDF ;(
– Blake Mills
Sep 28 '12 at 20:37
1
Re "mozilla docs for setDate() don't indicate that it will handle end of month scenarios". The "docs" have been updated so now they do. ;-)
– RobG
Dec 6 '16 at 23:15
I would link to the ECMAScript docs, but they are released in PDF ;(
– Blake Mills
Sep 28 '12 at 20:37
I would link to the ECMAScript docs, but they are released in PDF ;(
– Blake Mills
Sep 28 '12 at 20:37
1
1
Re "mozilla docs for setDate() don't indicate that it will handle end of month scenarios". The "docs" have been updated so now they do. ;-)
– RobG
Dec 6 '16 at 23:15
Re "mozilla docs for setDate() don't indicate that it will handle end of month scenarios". The "docs" have been updated so now they do. ;-)
– RobG
Dec 6 '16 at 23:15
add a comment |
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
add a comment |
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
add a comment |
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 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
edited Nov 13 '14 at 12:01
answered Oct 15 '14 at 19:06
Duncan
1,3101219
1,3101219
add a comment |
add a comment |
No, javascript has no a built in function, but
you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
add a comment |
No, javascript has no a built in function, but
you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
add a comment |
No, javascript has no a built in function, but
you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
No, javascript has no a built in function, but
you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
answered May 13 '16 at 16:11
Vahag Chakhoyan
11128
11128
add a comment |
add a comment |
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;
}
this should be marked as the correct answer
– Sérgio S. Filho
Sep 8 '18 at 16:07
add a comment |
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;
}
this should be marked as the correct answer
– Sérgio S. Filho
Sep 8 '18 at 16:07
add a comment |
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;
}
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;
}
answered Nov 25 '16 at 13:23
Joshua Comeau
1,1941016
1,1941016
this should be marked as the correct answer
– Sérgio S. Filho
Sep 8 '18 at 16:07
add a comment |
this should be marked as the correct answer
– Sérgio S. Filho
Sep 8 '18 at 16:07
this should be marked as the correct answer
– Sérgio S. Filho
Sep 8 '18 at 16:07
this should be marked as the correct answer
– Sérgio S. Filho
Sep 8 '18 at 16:07
add a comment |
I use something like:
new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)
Works with day saving time:
new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
Works with new year:
new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
It can be parametrized:
function DateAdd(source, amount, step) {
var factor = 1;
if (step == "day") factor = 24 * 60 * 60 * 1000;
else if (step == "hour") factor = 60 * 60 * 1000;
...
new Date(source.getTime() + amount * factor);
}
add a comment |
I use something like:
new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)
Works with day saving time:
new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
Works with new year:
new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
It can be parametrized:
function DateAdd(source, amount, step) {
var factor = 1;
if (step == "day") factor = 24 * 60 * 60 * 1000;
else if (step == "hour") factor = 60 * 60 * 1000;
...
new Date(source.getTime() + amount * factor);
}
add a comment |
I use something like:
new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)
Works with day saving time:
new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
Works with new year:
new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
It can be parametrized:
function DateAdd(source, amount, step) {
var factor = 1;
if (step == "day") factor = 24 * 60 * 60 * 1000;
else if (step == "hour") factor = 60 * 60 * 1000;
...
new Date(source.getTime() + amount * factor);
}
I use something like:
new Date(dateObject.getTime() + amountOfDays * 24 * 60 * 60 * 1000)
Works with day saving time:
new Date(new Date(2014, 2, 29, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
Works with new year:
new Date(new Date(2014, 11, 31, 20, 0, 0).getTime() + 1 * 24 * 60 * 60 * 1000)
It can be parametrized:
function DateAdd(source, amount, step) {
var factor = 1;
if (step == "day") factor = 24 * 60 * 60 * 1000;
else if (step == "hour") factor = 60 * 60 * 1000;
...
new Date(source.getTime() + amount * factor);
}
answered Jun 5 '14 at 10:05
kpull1
1,2751116
1,2751116
add a comment |
add a comment |
I am using the following solution.
var msInDay = 86400000;
var daysToAdd = 5;
var now = new Date();
var milliseconds = now.getTime();
var newMillisecods = milliseconds + msInDay * daysToAdd;
var newDate = new Date(newMillisecods);
//or now.setTime(newMillisecods);
Date has a constructor that accepts an int. This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object.
What we do here is convert days to milliseconds and add this value to the value provided by getTime. Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method.
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:00
Stephan, does any other library account for that?
– Vakhtang
Aug 24 '17 at 20:12
now.setDate(now.getDate() + days);
automatically handles DST changes. And I have to correct, leap seconds are ignored in JS timestamps.
– Stephan
Aug 25 '17 at 7:57
add a comment |
I am using the following solution.
var msInDay = 86400000;
var daysToAdd = 5;
var now = new Date();
var milliseconds = now.getTime();
var newMillisecods = milliseconds + msInDay * daysToAdd;
var newDate = new Date(newMillisecods);
//or now.setTime(newMillisecods);
Date has a constructor that accepts an int. This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object.
What we do here is convert days to milliseconds and add this value to the value provided by getTime. Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method.
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:00
Stephan, does any other library account for that?
– Vakhtang
Aug 24 '17 at 20:12
now.setDate(now.getDate() + days);
automatically handles DST changes. And I have to correct, leap seconds are ignored in JS timestamps.
– Stephan
Aug 25 '17 at 7:57
add a comment |
I am using the following solution.
var msInDay = 86400000;
var daysToAdd = 5;
var now = new Date();
var milliseconds = now.getTime();
var newMillisecods = milliseconds + msInDay * daysToAdd;
var newDate = new Date(newMillisecods);
//or now.setTime(newMillisecods);
Date has a constructor that accepts an int. This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object.
What we do here is convert days to milliseconds and add this value to the value provided by getTime. Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method.
I am using the following solution.
var msInDay = 86400000;
var daysToAdd = 5;
var now = new Date();
var milliseconds = now.getTime();
var newMillisecods = milliseconds + msInDay * daysToAdd;
var newDate = new Date(newMillisecods);
//or now.setTime(newMillisecods);
Date has a constructor that accepts an int. This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object.
What we do here is convert days to milliseconds and add this value to the value provided by getTime. Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method.
answered Jan 27 '15 at 12:13
Vakhtang
12228
12228
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:00
Stephan, does any other library account for that?
– Vakhtang
Aug 24 '17 at 20:12
now.setDate(now.getDate() + days);
automatically handles DST changes. And I have to correct, leap seconds are ignored in JS timestamps.
– Stephan
Aug 25 '17 at 7:57
add a comment |
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:00
Stephan, does any other library account for that?
– Vakhtang
Aug 24 '17 at 20:12
now.setDate(now.getDate() + days);
automatically handles DST changes. And I have to correct, leap seconds are ignored in JS timestamps.
– Stephan
Aug 25 '17 at 7:57
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:00
Not every day has 24h, it fails for DST and leap seconds.
– Stephan
Aug 24 '17 at 13:00
Stephan, does any other library account for that?
– Vakhtang
Aug 24 '17 at 20:12
Stephan, does any other library account for that?
– Vakhtang
Aug 24 '17 at 20:12
now.setDate(now.getDate() + days);
automatically handles DST changes. And I have to correct, leap seconds are ignored in JS timestamps.– Stephan
Aug 25 '17 at 7:57
now.setDate(now.getDate() + days);
automatically handles DST changes. And I have to correct, leap seconds are ignored in JS timestamps.– Stephan
Aug 25 '17 at 7:57
add a comment |
Edit:
Instead of setTime()
(or setHours()
) you could do it this way:
Date.prototype.addDays= function(d){
this.setDate(this.getDate() + d);
return this;
};
var tomorrow = new Date().addDays(1);
Old:
Instead of using setTime()
you can use setHours()
:
Date.prototype.addDays= function(d){
this.setHours(this.getHours() + d * 24);
return this;
};
var tomorrow = new Date().addDays(1);
See the JSFiddle...
following this logic you could also add one day ;)d.setDate(d.getDate() + 1);
– Rivenfall
Feb 24 '16 at 17:43
so true. edited!
– spaark
Feb 26 '16 at 9:58
add a comment |
Edit:
Instead of setTime()
(or setHours()
) you could do it this way:
Date.prototype.addDays= function(d){
this.setDate(this.getDate() + d);
return this;
};
var tomorrow = new Date().addDays(1);
Old:
Instead of using setTime()
you can use setHours()
:
Date.prototype.addDays= function(d){
this.setHours(this.getHours() + d * 24);
return this;
};
var tomorrow = new Date().addDays(1);
See the JSFiddle...
following this logic you could also add one day ;)d.setDate(d.getDate() + 1);
– Rivenfall
Feb 24 '16 at 17:43
so true. edited!
– spaark
Feb 26 '16 at 9:58
add a comment |
Edit:
Instead of setTime()
(or setHours()
) you could do it this way:
Date.prototype.addDays= function(d){
this.setDate(this.getDate() + d);
return this;
};
var tomorrow = new Date().addDays(1);
Old:
Instead of using setTime()
you can use setHours()
:
Date.prototype.addDays= function(d){
this.setHours(this.getHours() + d * 24);
return this;
};
var tomorrow = new Date().addDays(1);
See the JSFiddle...
Edit:
Instead of setTime()
(or setHours()
) you could do it this way:
Date.prototype.addDays= function(d){
this.setDate(this.getDate() + d);
return this;
};
var tomorrow = new Date().addDays(1);
Old:
Instead of using setTime()
you can use setHours()
:
Date.prototype.addDays= function(d){
this.setHours(this.getHours() + d * 24);
return this;
};
var tomorrow = new Date().addDays(1);
See the JSFiddle...
edited Feb 26 '16 at 9:57
answered Apr 9 '15 at 8:13
spaark
379415
379415
following this logic you could also add one day ;)d.setDate(d.getDate() + 1);
– Rivenfall
Feb 24 '16 at 17:43
so true. edited!
– spaark
Feb 26 '16 at 9:58
add a comment |
following this logic you could also add one day ;)d.setDate(d.getDate() + 1);
– Rivenfall
Feb 24 '16 at 17:43
so true. edited!
– spaark
Feb 26 '16 at 9:58
following this logic you could also add one day ;)
d.setDate(d.getDate() + 1);
– Rivenfall
Feb 24 '16 at 17:43
following this logic you could also add one day ;)
d.setDate(d.getDate() + 1);
– Rivenfall
Feb 24 '16 at 17:43
so true. edited!
– spaark
Feb 26 '16 at 9:58
so true. edited!
– spaark
Feb 26 '16 at 9:58
add a comment |
Very simple code to add days in date in java script.
var d = new Date();
d.setDate(d.getDate() + prompt('how many days you want to add write here'));
alert(d);
add a comment |
Very simple code to add days in date in java script.
var d = new Date();
d.setDate(d.getDate() + prompt('how many days you want to add write here'));
alert(d);
add a comment |
Very simple code to add days in date in java script.
var d = new Date();
d.setDate(d.getDate() + prompt('how many days you want to add write here'));
alert(d);
Very simple code to add days in date in java script.
var d = new Date();
d.setDate(d.getDate() + prompt('how many days you want to add write here'));
alert(d);
var d = new Date();
d.setDate(d.getDate() + prompt('how many days you want to add write here'));
alert(d);
var d = new Date();
d.setDate(d.getDate() + prompt('how many days you want to add write here'));
alert(d);
edited Feb 1 '17 at 18:57
Ruslan López
2,81811326
2,81811326
answered Sep 21 '16 at 6:04
Rana Aalamgeer
519518
519518
add a comment |
add a comment |
Our team considers date-fns the best library in this space. It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.
const newDate = DateFns.addDays(oldDate, 2);
add a comment |
Our team considers date-fns the best library in this space. It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.
const newDate = DateFns.addDays(oldDate, 2);
add a comment |
Our team considers date-fns the best library in this space. It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.
const newDate = DateFns.addDays(oldDate, 2);
Our team considers date-fns the best library in this space. It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.
const newDate = DateFns.addDays(oldDate, 2);
edited Jun 22 '17 at 20:52
answered Jun 6 '17 at 20:58
Luke Williams
1,2021028
1,2021028
add a comment |
add a comment |
There's a setDate and a getDate method, which allow you to do something like this :
var newDate = aDate.setDate(aDate.getDate() + numberOfDays);
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. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
(see also this Fiddle)
add a comment |
There's a setDate and a getDate method, which allow you to do something like this :
var newDate = aDate.setDate(aDate.getDate() + numberOfDays);
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. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
(see also this Fiddle)
add a comment |
There's a setDate and a getDate method, which allow you to do something like this :
var newDate = aDate.setDate(aDate.getDate() + numberOfDays);
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. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
(see also this Fiddle)
There's a setDate and a getDate method, which allow you to do something like this :
var newDate = aDate.setDate(aDate.getDate() + numberOfDays);
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. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
(see also this Fiddle)
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. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
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. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
answered Apr 16 '18 at 8:59
John Slegers
27.5k13146128
27.5k13146128
add a comment |
add a comment |
//the_day is 2013-12-31
var the_day = Date.UTC(2013, 11, 31);
// Now, the_day will be "1388448000000" in UTC+8;
var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
// Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"
I believe this wouldn't work with daylight saving times, leap seconds, or other timezone changes causing a day to not have 86400s.
– Nicolas Cortot
Dec 28 '13 at 16:29
This is the one that is correct. Date.UTC makes the difference. The only thing to that needs caution is that month starts from 0.
– Devid
Jan 24 '17 at 16:03
add a comment |
//the_day is 2013-12-31
var the_day = Date.UTC(2013, 11, 31);
// Now, the_day will be "1388448000000" in UTC+8;
var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
// Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"
I believe this wouldn't work with daylight saving times, leap seconds, or other timezone changes causing a day to not have 86400s.
– Nicolas Cortot
Dec 28 '13 at 16:29
This is the one that is correct. Date.UTC makes the difference. The only thing to that needs caution is that month starts from 0.
– Devid
Jan 24 '17 at 16:03
add a comment |
//the_day is 2013-12-31
var the_day = Date.UTC(2013, 11, 31);
// Now, the_day will be "1388448000000" in UTC+8;
var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
// Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"
//the_day is 2013-12-31
var the_day = Date.UTC(2013, 11, 31);
// Now, the_day will be "1388448000000" in UTC+8;
var the_next_day = new Date(the_day + 24 * 60 * 60 * 1000);
// Now, the_next_day will be "Wed Jan 01 2014 08:00:00 GMT+0800"
answered Dec 28 '13 at 15:59
cs1707
439134
439134
I believe this wouldn't work with daylight saving times, leap seconds, or other timezone changes causing a day to not have 86400s.
– Nicolas Cortot
Dec 28 '13 at 16:29
This is the one that is correct. Date.UTC makes the difference. The only thing to that needs caution is that month starts from 0.
– Devid
Jan 24 '17 at 16:03
add a comment |
I believe this wouldn't work with daylight saving times, leap seconds, or other timezone changes causing a day to not have 86400s.
– Nicolas Cortot
Dec 28 '13 at 16:29
This is the one that is correct. Date.UTC makes the difference. The only thing to that needs caution is that month starts from 0.
– Devid
Jan 24 '17 at 16:03
I believe this wouldn't work with daylight saving times, leap seconds, or other timezone changes causing a day to not have 86400s.
– Nicolas Cortot
Dec 28 '13 at 16:29
I believe this wouldn't work with daylight saving times, leap seconds, or other timezone changes causing a day to not have 86400s.
– Nicolas Cortot
Dec 28 '13 at 16:29
This is the one that is correct. Date.UTC makes the difference. The only thing to that needs caution is that month starts from 0.
– Devid
Jan 24 '17 at 16:03
This is the one that is correct. Date.UTC makes the difference. The only thing to that needs caution is that month starts from 0.
– Devid
Jan 24 '17 at 16:03
add a comment |
For those using Angular:
Just do:
$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);
$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);
add a comment |
For those using Angular:
Just do:
$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);
$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);
add a comment |
For those using Angular:
Just do:
$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);
$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);
For those using Angular:
Just do:
$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);
$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);
answered Jul 2 '15 at 10:18
user3806549
7801921
7801921
add a comment |
add a comment |
try this
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
Don't use this, in case of daylight saving setting this doesn't work because day difference is not 24h. I did the same mistake...
– Tobia
Jan 20 '18 at 7:09
add a comment |
try this
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
Don't use this, in case of daylight saving setting this doesn't work because day difference is not 24h. I did the same mistake...
– Tobia
Jan 20 '18 at 7:09
add a comment |
try this
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
try this
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
answered Nov 22 '17 at 14:12
LeMAK-Soft
391
391
Don't use this, in case of daylight saving setting this doesn't work because day difference is not 24h. I did the same mistake...
– Tobia
Jan 20 '18 at 7:09
add a comment |
Don't use this, in case of daylight saving setting this doesn't work because day difference is not 24h. I did the same mistake...
– Tobia
Jan 20 '18 at 7:09
Don't use this, in case of daylight saving setting this doesn't work because day difference is not 24h. I did the same mistake...
– Tobia
Jan 20 '18 at 7:09
Don't use this, in case of daylight saving setting this doesn't work because day difference is not 24h. I did the same mistake...
– Tobia
Jan 20 '18 at 7:09
add a comment |
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
add a comment |
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
add a comment |
You can use JavaScript, no jQuery required:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
Formatting to dd/mm/yyyy :
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
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;
answered Jul 14 '18 at 7:19
Rohit.007
1,6232419
1,6232419
add a comment |
add a comment |
You can create your custom helper function here
function plusToDate(currentDate, unit, howMuch) {
var config = {
second: 1000, // 1000 miliseconds
minute: 60000,
hour: 3600000,
day: 86400000,
week: 604800000,
month: 2592000000, // Assuming 30 days in a month
year: 31536000000 // Assuming 365 days in year
};
var now = new Date(currentDate);
return new Date(now + config[unit] * howMuch);
}
var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);
By the way, this is generic solution for adding seconds or minutes or days whatever you want.
Even assuming that a day has 86400 seconds can be incorrect, assuming that there are no leap years can lead to serious errors.
– Stephan
Aug 24 '17 at 12:46
...And also in case of daylight saving settings, difference between two day is not always 24h.
– Tobia
Jan 20 '18 at 7:10
add a comment |
You can create your custom helper function here
function plusToDate(currentDate, unit, howMuch) {
var config = {
second: 1000, // 1000 miliseconds
minute: 60000,
hour: 3600000,
day: 86400000,
week: 604800000,
month: 2592000000, // Assuming 30 days in a month
year: 31536000000 // Assuming 365 days in year
};
var now = new Date(currentDate);
return new Date(now + config[unit] * howMuch);
}
var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);
By the way, this is generic solution for adding seconds or minutes or days whatever you want.
Even assuming that a day has 86400 seconds can be incorrect, assuming that there are no leap years can lead to serious errors.
– Stephan
Aug 24 '17 at 12:46
...And also in case of daylight saving settings, difference between two day is not always 24h.
– Tobia
Jan 20 '18 at 7:10
add a comment |
You can create your custom helper function here
function plusToDate(currentDate, unit, howMuch) {
var config = {
second: 1000, // 1000 miliseconds
minute: 60000,
hour: 3600000,
day: 86400000,
week: 604800000,
month: 2592000000, // Assuming 30 days in a month
year: 31536000000 // Assuming 365 days in year
};
var now = new Date(currentDate);
return new Date(now + config[unit] * howMuch);
}
var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);
By the way, this is generic solution for adding seconds or minutes or days whatever you want.
You can create your custom helper function here
function plusToDate(currentDate, unit, howMuch) {
var config = {
second: 1000, // 1000 miliseconds
minute: 60000,
hour: 3600000,
day: 86400000,
week: 604800000,
month: 2592000000, // Assuming 30 days in a month
year: 31536000000 // Assuming 365 days in year
};
var now = new Date(currentDate);
return new Date(now + config[unit] * howMuch);
}
var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);
By the way, this is generic solution for adding seconds or minutes or days whatever you want.
answered Feb 25 '17 at 9:35
Jitesh Tukadiya
6691624
6691624
Even assuming that a day has 86400 seconds can be incorrect, assuming that there are no leap years can lead to serious errors.
– Stephan
Aug 24 '17 at 12:46
...And also in case of daylight saving settings, difference between two day is not always 24h.
– Tobia
Jan 20 '18 at 7:10
add a comment |
Even assuming that a day has 86400 seconds can be incorrect, assuming that there are no leap years can lead to serious errors.
– Stephan
Aug 24 '17 at 12:46
...And also in case of daylight saving settings, difference between two day is not always 24h.
– Tobia
Jan 20 '18 at 7:10
Even assuming that a day has 86400 seconds can be incorrect, assuming that there are no leap years can lead to serious errors.
– Stephan
Aug 24 '17 at 12:46
Even assuming that a day has 86400 seconds can be incorrect, assuming that there are no leap years can lead to serious errors.
– Stephan
Aug 24 '17 at 12:46
...And also in case of daylight saving settings, difference between two day is not always 24h.
– Tobia
Jan 20 '18 at 7:10
...And also in case of daylight saving settings, difference between two day is not always 24h.
– Tobia
Jan 20 '18 at 7:10
add a comment |
function addDays(n){
var t = new Date();
t.setDate(t.getDate() + n);
var month = "0"+(t.getMonth()+1);
var date = "0"+t.getDate();
month = month.slice(-2);
date = date.slice(-2);
var date = date +"/"+month +"/"+t.getFullYear();
alert(date);
}
addDays(5);
add a comment |
function addDays(n){
var t = new Date();
t.setDate(t.getDate() + n);
var month = "0"+(t.getMonth()+1);
var date = "0"+t.getDate();
month = month.slice(-2);
date = date.slice(-2);
var date = date +"/"+month +"/"+t.getFullYear();
alert(date);
}
addDays(5);
add a comment |
function addDays(n){
var t = new Date();
t.setDate(t.getDate() + n);
var month = "0"+(t.getMonth()+1);
var date = "0"+t.getDate();
month = month.slice(-2);
date = date.slice(-2);
var date = date +"/"+month +"/"+t.getFullYear();
alert(date);
}
addDays(5);
function addDays(n){
var t = new Date();
t.setDate(t.getDate() + n);
var month = "0"+(t.getMonth()+1);
var date = "0"+t.getDate();
month = month.slice(-2);
date = date.slice(-2);
var date = date +"/"+month +"/"+t.getFullYear();
alert(date);
}
addDays(5);
answered Aug 20 '17 at 13:05
Libu Mathew
1,8821321
1,8821321
add a comment |
add a comment |
1 2
next
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f563406%2fadd-days-to-javascript-date%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown