Reputation: 47
How can I add years to a date String in JavaScript?
Example:
var date = "01/01/1983"
I would like to add 26 to "1983". The result should be this "01/01/2009" String.
Could this be done with a replace() method instead of new Date()?
Upvotes: 1
Views: 186
Reputation: 4298
var parts ='01/01/1983'.split('/');
var mydate = new Date(parseInt(parts[2]) + 1, parts[1] - 1, parts[0]);
console.log(mydate.toDateString())
Upvotes: 0
Reputation: 370659
Yes, by providing a function to .replace
:
const input = "01/01/1983";
const output = input.replace(/\d+$/, year => Number(year) + 26);
console.log(output);
Upvotes: 3