Skip to content

Trying to add 5 years using moment

I am trying to add up to 5 years and each year it adds I am storing it to be displayed later.

const myDate = moment("2021-07-28", "YYYY-MM-DD");
const valid = myDate.isValid();

const addYear1 = myDate.add(1, 'y');
const firstYear = addYear1;
const addYear2 = firstYear.add(1, 'y');
const addYear3 = addYear2.add(1, 'y');
const addYear4 = addYear3.add(1, 'y');
const addYear5 = addYear4.add(1, 'y');

console.log("Year:", myDate);
console.log("is Year Valid:", valid);
console.log("Adding year1:", addYear1);
console.log("Adding year2:", addYear2);
console.log("Adding year3:", addYear3);
console.log("Adding year4:", addYear4);
console.log("Adding year5:", addYear5);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The output ends up being 2026 for all the outputs. I expecting to be:

Year: 2021
Adding year1: 2022
Adding year2: 2023
Adding year3: 2024
Adding year4: 2025
Adding year5: 2026

Answer

Try the following:

const addYear1 = myDate.add(1,'y').format('YYYY'); // 2022
const addYear2 = myDate.add(1, 'y').format('YYYY'); // 2023
const addYear3 = myDate.add(1, 'y').format('YYYY'); // 2024
const addYear4 = myDate.add(1, 'y').format('YYYY'); // 2025
const addYear5 = myDate.add(1, 'y').format('YYYY'); // 2026

Just re-use the original moment object and modify it each time you want to use it.