sapientZero
sapientZero

Reputation: 47

Adding years to a date string?

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

Answers (2)

programtreasures
programtreasures

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

CertainPerformance
CertainPerformance

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

Related Questions