var date = new Date(); // Now
date.setDate(date.getDate() + 30); // Set now + 30 days as the new date
console.log(date);
Answer from Lennholm on Stack OverflowVideos
Updated answer (2018)
One way to add 30 days to a date string is to parse it to a Date, add 30 days, then format it back to a string.
Date strings should be parsed manually, either with a bespoke function or a library. Either way, you need to know the format to know if it's been parsed correctly, e.g.
// Given a string in m/d/y format, return a Date
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[0]-1, b[1]);
}
// Given a Date, return a string in m/d/y format
function formatMDY(d) {
function z(n){return (n<10?'0':'')+n}
if (isNaN(+d)) return d.toString();
return z(d.getMonth()+1) + '/' + z(d.getDate()) + '/' + d.getFullYear();
}
// Given a string in m/d/y format, return a string in the same format with n days added
function addDays(s, days) {
var d = parseMDY(s);
d.setDate(d.getDate() + Number(days));
return formatMDY(d);
}
[['6/30/2018', 30],
['1/30/2018', 30], // Goes from 30 Jan to 1 Mar
['12/31/2019', 30]].forEach(a => {
console.log(`
{addDays(...a)}`);
});
If the "30 days" criterion is interpreted as adding a month, that is a bit trickier. Adding 1 month to 31 January will give 31 February, which resolves to 2 or 3 March depending on whether February for that year has 28 or 29 days. One algorithm to resolve that is to see if the month has gone too far and set the date to the last day of the previous month, so 2018-01-31 plus one month gives 2018-02-28.
The same algorithm works for subtracting months, e.g.
/**
* @param {Date} date - date to add months to
* @param {number} months - months to add
* @returns {Date}
*/
function addMonths(date, months) {
// Deal with invalid Date
if (isNaN(+date)) return;
months = parseInt(months);
// Deal with months not being a number
if (isNaN(months)) return;
// Store date's current month
var m = date.getMonth();
date.setMonth(date.getMonth() + months);
// Check new month, if rolled over an extra month,
// go back to last day of previous month
if (date.getMonth() != (m + 12 + months)%12) {
date.setDate(0);
}
// date is modified in place, but return for convenience
return date;
}
// Helper to format the date as D-MMM-YYYY
// using browser default language
function formatDMMMY(date) {
var month = date.toLocaleString(undefined,{month:'short'});
return date.getDate() + '-' + month + '-' + date.getFullYear();
}
// Some tests
[[new Date(2018,0,31), 1],
[new Date(2017,11,31), 2],
[new Date(2018,2,31), -1],
[new Date(2018,6,31), -1],
[new Date(2018,6,31), -17]].forEach(a => {
let f = formatDMMMY;
console.log(`${f(a[0])} plus ${a[1]} months: ${f(addMonths(...a))}`);
});
Of course a library can help with the above, the algorithms are the same.
Original answer (very much out of date now)
Simply add 30 days to todays date:
var now = new Date();
now.setDate(now.getDate() + 30);
However, is that what you really want to do? Or do you want to get today plus one month?
You can convert a d/m/y date to a date object using:
var dString = '9/5/2011';
var dParts = dString.split('/');
var in30Days = new Date(dParts[2] + '/' +
dParts[1] + '/' +
(+dParts[0] + 30)
);
For US date format, swap parts 0 and 1:
var in30Days = new Date(dParts[2] + '/' +
dParts[0] + '/' +
(+dParts[1] + 30)
);
But it is better to get the date into an ISO8601 format before giving it to the function, you really shouldn't be mixing date parsing and arithmetic in the same function. A comprehensive date parsing function is complex (not excessively but they are tediously long and need lots of testing), arithmetic is quite simple once you have a date object.
A simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Then, you need the current timestamp:
Date.now()
Finally, sum both values and send the result as a param in the constructor:
var nowPlus30Days = new Date(Date.now() + (30 * 24 * 60 * 60 * 1000));
You can create one using Date.prototype.setDate():
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, as noted here. For example:
8/31 + 1 day will become 9/1.
The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.
Correct Answer:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
Incorrect Answer:
This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.
// Don't do it this way!
function addDaysWRONG(date, days) {
var result = new Date(); // not instatiated with date!!! DANGER
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>
For leading zeros:
// add leading zero if the length equals 1
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
Be sure to add 1 to your month prior to using this code, too, since getMonth() returns a 0 for January, and so on:
var month = d.getMonth() + 1;
Surprise, surprise... The getMonth() method returns the month in the range 0..11.
You can follow this approach
- parse the input date value to date using
splitand date constructor - Add days using
setDate - Set the new date value to output date.
Demo
document.querySelector("#addDays").addEventListener("click", function() {
var invoiceDate = document.querySelector("#invoiceDate").value;
var days = Number(document.querySelector("#days").value);
var dueDateElement = document.querySelector("#dueDate");
if (!isNaN(days) && invoiceDate.length) {
invoiceDate = invoiceDate.split("-");
invoiceDate = new Date(invoiceDate[0], invoiceDate[1] - 1, invoiceDate[2]);
invoiceDate.setDate(invoiceDate.getDate() + days);
dueDateElement.valueAsDate = null;
dueDateElement.valueAsDate = invoiceDate;
//console.log(invoiceDate, dueDateElement.value);
}
});
Invoice Date <input type="date" id="invoiceDate"> <br><br> Add Days <input type="text" id="days"> <br><br>
<button id="addDays">Add Days</button> <br><br> Due Date <input type="date" id="dueDate">
You can create the date in Javascript like this
var date = new Date(2017,11,27,11,14,00,00)
you can add 30 days to this date to get the date (after 30 days)
after30days = date.setDate(cur.getDate() + 30);
setDate() doesn't return a Date object, it returns the number of milliseconds since 1 January 1970 00:00:00 UTC. You need separate calls:
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2016-06-08"
You're saying that those two lines worked for you and your problem is combining them. Here is how you do that:
var date = new Date();
date.setDate(date.getDate() - 30);
document.getElementById("result").innerHTML = date.toISOString().split('T')[0];
<div id="result"></div>
If you really want to subtract exactly 30 days, then this code is fine, but if you want to subtract a month, then obviously this code doesn't work and it's better to use a library like moment.js as other have suggested than trying to implement it by yourself.