Sometimes, we want to add 30 days to date in mm/dd/yy format with JavaScript.
In this article, we’ll look at how to add 30 days to date in mm/dd/yy format with JavaScript.
How to add 30 days to date in mm/dd/yy format with JavaScript?
To add 30 days to date in mm/dd/yy format with JavaScript, we can parse the date, get its timestamp, and then we can add the days to it.
For instance, we write:
const s = '12/31/21'
const [month, day, year] = s.split(/D/);
const d = new Date(+year.toString().padStart(4, '20'), month - 1, day)
const newD = new Date(d.getTime() + 30 * 24 * 60 * 60 * 1000)
console.log(newD)
to get the 3 numerical parts of string s with split.
Then we create date d with +year.toString().padStart(4, '20') to prepend the 2 digit year with 20.
The 2nd argument is month - 1 since JavaScript dates are zero based.
And we pass in the day as is.
Next, we call getTime to get the timestamp of d in milliseconds.
And then we add 30 days to it by adding 30 * 24 * 60 * 60 * 1000.
As a result, newD is Sun Jan 30 2022 00:00:00 GMT-0800 (Pacific Standard Time).
Conclusion
To add 30 days to date in mm/dd/yy format with JavaScript, we can parse the date, get its timestamp, and then we can add the days to it.