1

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()?

2 Answers2

3

Yes, by providing a function to .replace:

const input = "01/01/1983";
const output = input.replace(/\d+$/, year => Number(year) + 26);
console.log(output);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

var parts ='01/01/1983'.split('/');
var mydate = new Date(parseInt(parts[2]) + 1, parts[1] - 1, parts[0]); 
console.log(mydate.toDateString())
programtreasures
  • 4,250
  • 1
  • 10
  • 29
  • Thank you, but the output of your code is Sun Jan 01 1984 (timestamp) which I can't utilize. I require "01/01/2009" as a String. – sapientZero Jun 02 '18 at 04:41