Home > OS >  I want to be able to show a company's year of start to the current year
I want to be able to show a company's year of start to the current year

Time:11-09

If a company was registered in a particular year, I want to be able to show the company's year registered through to the current year. for example if a company was registered in let's say 2018; i want to be able to have something like 2018, 2019, 2020, 2021. So i have a function that is able to get only the current year. So want a way i can achieve this.

This is a function i have which works fine because it gives me the current year.

getLastYear() {
    const now = new Date();
    const currentYear = now.getFullYear();

    return currentYear - 1;
  }

CodePudding user response:

In order to get an array of calendar years you can take the start year and the current year and iterate over the difference:

const startYear = 2015 // load from database or set some other way

const getArrayOfYears = (startYear: int): int[] => {
  const currentYear = new Date().getFullYear()

  let arrayOfYears = []: int[]
  for (let year = startYear; year <= currentYear; year  ) {
    arrayOfYears.push(year)
  }
  return arrayOfYears
}

console.log(JSON.stringify(getArrayOfYears(startYear)))

There are many alternatives to using a for loop but most of them are some combination of hard to read, overly complicated, slow, or ugly. Sometimes it's best to stick with the basics.

  • Related