Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  155] [ 2]  / answers: 1 / hits: 45599  / 13 Years ago, sun, may 8, 2011, 12:00:00

I have a date in the format mm/dd/yy and want to add 30 days to it. I am just curious the best method to do this? I am new to javascript so examples would be helpful.



EDITED



Sorry I am using US date format mm/dd/yy.


More From » date

 Answers
5

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(`${a[0]} => ${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.


[#92341] Friday, May 6, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhett

Total Points: 671
Total Questions: 100
Total Answers: 102

Location: Hong Kong
Member since Tue, Oct 19, 2021
3 Years ago
;