How to create a function in javascript that will return a date 12 months one day ahead of current date? It should handle edge cases like if i select date as 2024-02-29 then it should return 2025-03-01. If i select date as 2024-07-31 then it should return 2025-08-01?
let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth();
let currentDateOfMonth = currentDate.getDate();
let targetMonth = currentMonth + 12;
let targetDate = currentDateOfMonth + 1;
if (targetMonth >= 12) {
currentYear++;
targetMonth -= 12;
}
let daysInTargetMonth = new Date(currentYear, targetMonth + 1, 0).getDate();
if (targetDate > daysInTargetMonth) {
targetDate = targetDate - daysInTargetMonth;
targetMonth++;
if (targetMonth >= 12) {
currentYear++;
targetMonth -= 12;
}
}
let targetDateObj = new Date(currentYear, targetMonth,
targetDate);
console.log(targetDateObj.toLocaleDateString());
Tried the above code but when i pass the date as 2024-02-29 it returns me 3/2/2025 instead of 1/3/2025. What is wrong with the code?