MenimE
MenimE

Reputation: 304

Display previous year and current year in angular

I am trying to get the previous year and current year in the format "2019-20". Is there an easy way to do this. I have written a code but its returning 2020-21.

  getCurrentFinancialYear2() {
    var fiscalyear_ = "";
    var today = new Date();
    if ((today.getMonth() + 1) <= 3) {
      fiscalyear_ = ((today.getFullYear() - 1) + "") + "-" + (today.getFullYear() + "").slice(-2)
    } else {
      fiscalyear_ = (today.getFullYear() + "") + "-" + ((today.getFullYear() + 1) + "").slice(-2)
    }
    this.year_ = fiscalyear_
    
    return fiscalyear_
    
  }

Any easier way to achieve this?

Upvotes: 1

Views: 4392

Answers (2)

RobG
RobG

Reputation: 147423

If you're only concerned with modern years then you can just get the current year, subtract one and concatenate the last two digits of the current, e.g.

function getFY(year = new Date().getFullYear()){
  return `${year - 1}-${String(year).slice(-2)}`; 
}

console.log(getFY());       // Default: current year
console.log(getFY(2021));   // Year as number
console.log(getFY('2022')); // Year as string

If you want to handle the full range of possible years (approximately ±285,426 from 1970), you'll need to do a little more work.

Upvotes: 2

Kyrill
Kyrill

Reputation: 366

function getCurrentFinancialYear() {
  const thisYear = (new Date()).getFullYear();
  const lastYear = thisYear-1;
  return `${lastYear}-${thisYear.toString().slice(-2)}`;
}

console.log(getCurrentFinancialYear());

Upvotes: 1

Related Questions