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

3
  • is your date mm/dd/yyyy format? Commented Jun 2, 2018 at 4:25
  • Possible duplicate of Add year to todays date Commented Jun 2, 2018 at 4:27
  • @Leogoesger: Quetion specifically mention no new Date() Commented Jun 2, 2018 at 4:29

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

var parts ='01/01/1983'.split('/');
var mydate = new Date(parseInt(parts[2]) + 1, parts[1] - 1, parts[0]); 
console.log(mydate.toDateString())

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.