Home > Back-end >  Trying to add 5 years using moment
Trying to add 5 years using moment

Time:02-05

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

CodePudding user response:

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.

CodePudding user response:

Not sure about using moment but using vanilla js you can use this

const date = new Date();
console.log(date.toString())
date.setFullYear(date.getFullYear()   1)
console.log(date.toString())

You can pass any string inside Date() to set it manually.

CodePudding user response:

add Mutates the original moment by adding time (docs).

Each time you add you're not doing so in isolation, you're using the same object. All of your consts hold references to the same moment object.

To make a real copy of the moment object, you'd need to use clone:

const firstYear = addYear1;
// to 
const firstYear = addYear1.clone();

Your final result could be something like this:

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

Or just using the same base object and adding different years:

const myDate = moment("2021-07-28", "YYYY-MM-DD");
const addYear2 = myDate.clone().add(2, 'y');
const addYear3 = myDate.clone().add(3, 'y');
const addYear4 = myDate.clone().add(4, 'y');
const addYear5 = myDate.clone().add(5, 'y');

Also see this related issue.

  •  Tags:  
  • Related