How to add days to Date?
JavascriptDateJavascript Problem Overview
How to add days to current Date
using JavaScript? Does JavaScript have a built in function like .NET's AddDay()
?
Javascript Solutions
Solution 1 - Javascript
You can create one with:-
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
console.log(date.addDays(5));
This takes care of automatically incrementing the month if necessary. For example:
8/31 + 1 day will become 9/1.
The problem with using setDate
directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date
as a mutable class rather than an immutable structure.
Solution 2 - Javascript
Correct Answer:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
Incorrect Answer:
This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.
// Don't do it this way!
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
Proof / Example
// Correct
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// Bad Year/Month
function addDaysWRONG(date, days) {
var result = new Date();
result.setDate(date.getDate() + days);
return result;
}
// Bad during DST
function addDaysDstFail(date, days) {
var dayms = (days * 24 * 60 * 60 * 1000);
return new Date(date.getTime() + dayms);
}
// TEST
function formatDate(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
}
$('tbody tr td:first-child').each(function () {
var $in = $(this);
var $out = $('<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>
Solution 3 - Javascript
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
Be careful, because this can be tricky. When setting tomorrow
, it only works because its current value matches the year and month for today
. However, setting to a date number like "32" normally will still work just fine to move it to the next month.
Solution 4 - Javascript
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.
Solution 5 - Javascript
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.
Solution 6 - Javascript
Here is the way that use to add days, months, and years for a particular date in Javascript.
// To add Days
var d = new Date();
d.setDate(d.getDate() + 5);
// To add Months
var m = new Date();
m.setMonth(m.getMonth() + 5);
// To add Years
var y = new Date();
y.setFullYear(y.getFullYear() + 5);
Solution 7 - Javascript
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.
Solution 8 - Javascript
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.
Solution 9 - Javascript
The simplest approach that I have implemented is to use Date() itself. `
const days = 15;
// Date.now() gives the epoch date value (in milliseconds) of current date
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)
`
Solution 10 - Javascript
int days = 1;
var newDate = new Date(Date.now() + days * 24*60*60*1000);
var days = 2;
var newDate = new Date(Date.now() + days * 24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);
Solution 11 - Javascript
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/
Solution 12 - Javascript
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;
}
Solution 13 - Javascript
A solution designed for the pipeline operator:
const addDays = days => date => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
Usage:
// Without the pipeline operator...
addDays(7)(new Date());
// And with the pipeline operator...
new Date() |> addDays(7);
If you need more functionality, I suggest looking into the date-fns library.
Solution 14 - Javascript
the simplest answer is, assuming the need is to add 1 day to the current date:
var currentDate = new Date();
var numberOfDayToAdd = 1;
currentDate.setDate(currentDate.getDate() + numberOfDayToAdd );
To explain to you, line by line, what this code does:
- Create the current date variable named currentDate. By default "new Date()" automatically assigns the current date to the variable.
- Create a variable to save the number of day(s) to add to the date (you can skip this variable and use directly the value in the third line)
- Change the value of Date (because Date is the number of the month's day saved in the object) by giving the same value + the number you want. The switch to the next month will be automatic
Solution 15 - Javascript
Without using the second variable, you can replace 7 with your next x days:
let d=new Date(new Date().getTime() + (7 * 24 * 60 * 60 * 1000));
Solution 16 - Javascript
to substract 30 days use (24h=86400000ms)
new Date(+yourDate - 30 *86400000)
var yourDate=new Date();
var d = new Date(+yourDate - 30 *86400000)
console.log(d)
Solution 17 - Javascript
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);
Solution 18 - Javascript
Late to the party, but if you use there's an excellent plugin called Moment:jQuery
then
var myDateOfNowPlusThreeDays = moment().add(3, "days").toDate();
http://momentjs.com/docs/#/manipulating/
And lots of other good stuff in there!
Edit: jQuery reference removed thanks to aikeru's comment
Solution 19 - Javascript
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;
Solution 20 - Javascript
As simple as this:
new Date((new Date()).getTime() + (60*60*24*1000));
Solution 21 - Javascript
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;
}
Solution 22 - Javascript
Old I know, but sometimes I like this:
function addDays(days) {
return new Date(Date.now() + 864e5 * days);
}
Solution 23 - Javascript
No, javascript has no a built in function, but you can use a simple line of code
timeObject.setDate(timeObject.getDate() + countOfDays);
Solution 24 - Javascript
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;
}
Solution 25 - Javascript
Why so complicated?
Let's assume you store the number of days to add in a variable called days_to_add.
Then this short one should do it:
calc_date = new Date(Date.now() +(days_to_add * 86400000));
With Date.now() you get the actual unix timestamp as milliseconds and then you add as many milliseconds as you want to add days to. One day is 24h60min60s*1000ms = 86400000 ms or 864E5.
Solution 26 - Javascript
Generic prototype with no variables, it applies on an existing Date value:
Date.prototype.addDays = function (days) {
return new Date(this.valueOf() + days * 864e5);
}
Solution 27 - Javascript
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.
Solution 28 - Javascript
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
Solution 29 - Javascript
Short:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(newDate.getDate() + number));
}
console.log({
tomorrow: addDays(new Date(), 1)
});
Advance:
function addDays(date, number) {
const newDate = new Date(date);
return new Date(newDate.setDate(date.getDate() + number));
}
function addMonths(date, number) {
const newDate = new Date(date);
return new Date(newDate.setMonth(newDate.getMonth() + number));
}
function addYears(date, number) {
const newDate = new Date(date);
return new Date(newDate.setFullYear(newDate.getFullYear() + number));
}
function getNewDate(dateTime) {
let date = new Date();
let number = parseInt(dateTime.match(/\d+/)[0]);
if (dateTime.indexOf('-') != -1)
number = (- number);
if (dateTime.indexOf('day') != -1)
date = addDays(date, number);
else if (dateTime.indexOf('month') != -1)
date = addMonths(date, number);
else if (dateTime.indexOf('year') != -1)
date = addYears(date, number);
return date;
}
console.log({
tomorrow: getNewDate('+1day'),
yesterday: getNewDate('-1day'),
nextMonth: getNewDate('+1month'),
nextYear: getNewDate('+1year'),
});
With fix provide by jperl
Solution 30 - Javascript
You can try:
var days = 50;
const d = new Date();
d.setDate(d.getDate() + days)
This should work well.
Solution 31 - Javascript
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);
}
Solution 32 - Javascript
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...
Solution 33 - Javascript
Extending prototype in javascript may not be a good idea, especially in professional codebases.
What you want to do is extend the native Date
class:
class MyCustomDate extends Date {
addDays(days) {
const date = new MyCustomDate(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
}
const today = new MyCustomDate();
const nextWeek = today.addDays(7)
console.log(nextWeek)
This way, if one day Javascript implements a native addDays
method, you won't break anything.
Solution 34 - Javascript
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);
Solution 35 - Javascript
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)
Solution 36 - Javascript
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.
Solution 37 - Javascript
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);
Solution 38 - Javascript
There is a problem with this kind of functions, I solve it with parseInt()
Date.prototype.addDays = function(dias) {
var date = new Date(this.valueOf());
date.setDate(parseInt(date.getDate()) + parseInt(dias));
return date;
}
Date.prototype.addMonths = function(months) {
var date = new Date(this.valueOf());
date.setMonth(parseInt(date.getMonth()) + parseInt(months));
return date;
}
Date.prototype.addYears = function(years) {
var date = new Date(this.valueOf());
date.setFullYear(parseInt(date.getFullYear()) + parseInt(years));
return date;
}
Solution 39 - Javascript
//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"
Solution 40 - Javascript
For those using Angular:
Just do:
$scope.booking.totTijd.setMinutes($scope.booking.totTijd.getMinutes()+15);
$scope.booking.totTijd.setDate($scope.booking.totTijd.getDate() + 1);
Solution 41 - Javascript
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.
Solution 42 - Javascript
I've used this approach to get the right date in one line to get the time plus one day following what people were saying above.
((new Date()).setDate((new Date()).getDate()+1))
I just figured I would build off a normal (new Date())
:
(new Date()).getDate()
> 21
Using the code above I can now set all of that within Date()
in (new Date())
and it behaves normally.
(new Date(((new Date()).setDate((new Date()).getDate()+1)))).getDate()
> 22
or to get the Date
object:
(new Date(((new Date()).setDate((new Date()).getDate()+1))))
Solution 43 - Javascript
I can't believe there's no cut'n'paste solution in this thread after 5 years!
SO: To get the same time-of-day regardless of summertime interference:
Date.prototype.addDays = function(days)
{
var dat = new Date( this.valueOf() )
var hour1 = dat.getHours()
dat.setTime( dat.getTime() + days * 86400000) // 24*60*60*1000 = 24 hours
var hour2 = dat.getHours()
if (hour1 != hour2) // summertime occured +/- a WHOLE number of hours thank god!
dat.setTime( dat.getTime() + (hour1 - hour2) * 3600000) // 60*60*1000 = 1 hour
return dat
or
this.setTime( dat.getTime() ) // to modify the object directly
}
There. Done!
Solution 44 - Javascript
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);
Solution 45 - Javascript
The easiest way to get this done is using date-fns library.
var addDays = require('date-fns/add_days')
addDays(date, amount)
The documentation is available in this link here. You can also get this done using moment.js. The reference link is here
Hope it helps!
Solution 46 - Javascript
Some implementations to extend Date https://gist.github.com/netstart/c92e09730f3675ba8fb33be48520a86d
/**
* just import, like
*
* import './../shared/utils/date.prototype.extendions.ts';
*/
declare global {
interface Date {
addDays(days: number, useThis?: boolean): Date;
addSeconds(seconds: number): Date;
addMinutes(minutes: number): Date;
addHours(hours: number): Date;
addMonths(months: number): Date;
isToday(): boolean;
clone(): Date;
isAnotherMonth(date: Date): boolean;
isWeekend(): boolean;
isSameDate(date: Date): boolean;
getStringDate(): string;
}
}
Date.prototype.addDays = function(days: number): Date {
if (!days) {
return this;
}
this.setDate(this.getDate() + days);
return this;
};
Date.prototype.addSeconds = function(seconds: number) {
let value = this.valueOf();
value += 1000 * seconds;
return new Date(value);
};
Date.prototype.addMinutes = function(minutes: number) {
let value = this.valueOf();
value += 60000 * minutes;
return new Date(value);
};
Date.prototype.addHours = function(hours: number) {
let value = this.valueOf();
value += 3600000 * hours;
return new Date(value);
};
Date.prototype.addMonths = function(months: number) {
const value = new Date(this.valueOf());
let mo = this.getMonth();
let yr = this.getYear();
mo = (mo + months) % 12;
if (0 > mo) {
yr += (this.getMonth() + months - mo - 12) / 12;
mo += 12;
} else {
yr += ((this.getMonth() + months - mo) / 12);
}
value.setMonth(mo);
value.setFullYear(yr);
return value;
};
Date.prototype.isToday = function(): boolean {
const today = new Date();
return this.isSameDate(today);
};
Date.prototype.clone = function(): Date {
return new Date(+this);
};
Date.prototype.isAnotherMonth = function(date: Date): boolean {
return date && this.getMonth() !== date.getMonth();
};
Date.prototype.isWeekend = function(): boolean {
return this.getDay() === 0 || this.getDay() === 6;
};
Date.prototype.isSameDate = function(date: Date): boolean {
return date && this.getFullYear() === date.getFullYear() && this.getMonth() === date.getMonth() && this.getDate() === date.getDate();
};
Date.prototype.getStringDate = function(): string {
// Month names in Brazilian Portuguese
const monthNames = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
// Month names in English
// let monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const today = new Date();
if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay()) {
return 'Hoje';
// return "Today";
} else if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay() + 1) {
return 'Amanhã';
// return "Tomorrow";
} else if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay() - 1) {
return 'Ontem';
// return "Yesterday";
} else {
return this.getDay() + ' de ' + this.monthNames[this.getMonth()] + ' de ' + this.getFullYear();
// return this.monthNames[this.getMonth()] + ' ' + this.getDay() + ', ' + this.getFullYear();
}
};
export {};
Solution 47 - Javascript
2.39KB minified. One file. https://github.com/rhroyston/clock-js
console.log(clock.what.weekday(clock.now + clock.unit.days)); //"wednesday"
console.log(clock.what.weekday(clock.now + (clock.unit.days * 2))); //"thursday"
console.log(clock.what.weekday(clock.now + (clock.unit.days * 3))); //"friday"
<script src="https://raw.githubusercontent.com/rhroyston/clock-js/master/clock.min.js"></script>
Solution 48 - Javascript
try this
function addDays(date,days) {
var one_day=1000*60*60*24;
return new Date(date.getTime()+(days*one_day)).toLocaleDateString();
}
Solution 49 - Javascript
Use js-joda. It is an awesome immutable date and time library for javascript. Here is an excerpt from its cheat-sheet.
Add 17 days to today
LocalDate.now().plusDays(17);
You can also build the desired date from now multiple operations at once.
LocalDate.now()
.plusMonths(1)
.withDayOfMonth(1)
.minusDays(17);
Or:
var d = LocalDate.parse('2019-02-23');
d.minus(Period.ofMonths(3).plusDays(3)); // '2018-11-20'
Solution 50 - Javascript
My test exemple can do adition an minus in the same instance of Date Object.
Date.prototype.reset = function()
{
let newDate = new Date(this.timeStamp)
this.setFullYear (newDate.getFullYear())
this.setMonth (newDate.getMonth())
this.setDate (newDate.getDate())
this.setHours (newDate.getHours())
this.setMinutes (newDate.getMinutes())
this.setSeconds (newDate.getSeconds())
this.setMilliseconds (newDate.getMilliseconds())
}
Date.prototype.addDays = function(days)
{
this.timeStamp = this[Symbol.toPrimitive]('number')
let daysInMiliseconds = (days * (1000 * 60 * 60 * 24))
this.timeStamp = this.timeStamp + daysInMiliseconds
this.reset()
}
Date.prototype.minusDays = function(days)
{
this.timeStamp = this[Symbol.toPrimitive]('number')
let daysInMiliseconds = (days * (1000 * 60 * 60 * 24))
if(daysInMiliseconds <= this.timeStamp)
{
this.timeStamp = this.timeStamp - daysInMiliseconds
this.reset()
}
}
var temp = new Date(Date.now())// from now time
console.log(temp.toDateString())
temp.addDays(31)
console.log(temp.toDateString())
temp.minusDays(5)
console.log(temp.toDateString())
Solution 51 - Javascript
I was trying to solve something similar, I prefer the getTime methods but there are some odd time zone based side effects.
ofc replace "today" with whatever date you need and pass the time in also. The key is to get UTC Time and then use milliseconds to do the addition to bypass those side effects.
var now = new Date(Date.now());
var today = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
const dayInMs = 86400000; //24 hours
const tomorrow = new Date(today.getTime() + dayInMs);
Solution 52 - Javascript
I sum hours and days...
Date.prototype.addDays = function(days){
days = parseInt(days, 10)
this.setDate(this.getUTCDate() + days);
return this;
}
Date.prototype.addHours = function(hrs){
var hr = this.getUTCHours() + parseInt(hrs , 10);
while(hr > 24){
hr = hr - 24;
this.addDays(1);
}
this.setHours(hr);
return this;
}
Solution 53 - Javascript
For everybody who don't know how to make it work : there is a full working code it's not perfect but you can copy past it and it's working.
In InDesign creat a .jsx
in the startup scripts folder in "Program Files\Adobe\Adobe InDesign 2021\Scripts\startup scripts"
.
You can us the Extendscript Toolkit CC in the creative cloud to make it and paste this:
The restart indesign and jjmmyyyy
+30 should be in the texte variable.
this will show the date like this jj/m/yyyy
idk how to make it show 24/07/2021
insted of 24/7/2021
but goodenough for me .
#targetengine 'usernameVariable'
function addVariables(openEvent)
{
var doc = openEvent.parent;
while ( doc.constructor.name != "Document" )
{
if ( doc.constructor.name == "Application" ){ return; }
doc = doc.parent;
}
// from http://stackoverflow.com/questions/563406/add-days-to-datetime
var someDate = new Date();
var numberOfDaysToAdd = 30;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
createTextVariable(doc, "jjmmyyyy+30", someFormattedDate);
}
function createTextVariable(target, variableName, variableContents)
{
var usernameVariable = target.textVariables.itemByName(variableName);
if (!usernameVariable.isValid)
{
usernameVariable = target.textVariables.add();
usernameVariable.variableType = VariableTypes.CUSTOM_TEXT_TYPE;
usernameVariable.name = variableName;
}
usernameVariable.variableOptions.contents = variableContents;
}
app.addEventListener('afterOpen', addVariables);
Solution 54 - Javascript
https://stackoverflow.com/questions/3818193/how-to-add-number-of-days-to-todays-date
the same answer: function DaysOfMonth(nYear, nMonth) {
switch (nMonth) {
case 0: // January
return 31; break;
case 1: // February
if ((nYear % 4) == 0) {
return 29;
}
else {
return 28;
};
break;
case 2: // March
return 31; break;
case 3: // April
return 30; break;
case 4: // May
return 31; break;
case 5: // June
return 30; break;
case 6: // July
return 31; break;
case 7: // August
return 31; break;
case 8: // September
return 30; break;
case 9: // October
return 31; break;
case 10: // November
return 30; break;
case 11: // December
return 31; break;
}
};
function SkipDate(dDate, skipDays) {
var nYear = dDate.getFullYear();
var nMonth = dDate.getMonth();
var nDate = dDate.getDate();
var remainDays = skipDays;
var dRunDate = dDate;
while (remainDays > 0) {
remainDays_month = DaysOfMonth(nYear, nMonth) - nDate;
if (remainDays > remainDays_month) {
remainDays = remainDays - remainDays_month - 1;
nDate = 1;
if (nMonth < 11) { nMonth = nMonth + 1; }
else {
nMonth = 0;
nYear = nYear + 1;
};
}
else {
nDate = nDate + remainDays;
remainDays = 0;
};
dRunDate = Date(nYear, nMonth, nDate);
}
return new Date(nYear, nMonth, nDate);
};