How to convert String to date and add a year to this date in javascript

advertisements

I have this String 29/06/2017i want to convert it into JavaScript date and add one year to it results Should be 28/06/2018 how to do it . i have tried this

var MyDate = new Date('29/06/2017');

Output is invalid date object how to convert it and add one year.


You can try to switch the Day and the Year

var date = new Date('29/06/2017'.split('/').reverse().join('/'));
var plusOneYear = date.setFullYear(date.getFullYear()+1);
console.log(date); // output: Fri Jun 29 2018 00:00:00
console.log(new Date(plusOneYear)); // output: Fri Jun 29 2018 00:00:00
console.log(date.toLocaleDateString()) // output: 6/29/2018
console.log(date.getDate() + '/' + (date.getMonth+1) + '/' + date.getFullYear()); // output: 29/6/2018

another way is

var date = '29/06/2017'.split('/'); // will become [day][month][year]
var newDate = date[2] + '/' + date[1] + '/' + date[0]; // join in format you would prefer
var plusOneYear = newDate.setFullYear(newDate.getFullYear()+1);
console.log(new Date(plusOneYear));
console.log(newDate.toLocaleDateString()) // output: 6/29/2018

Edited