How do I display the last month with the year?

Viewed 42

I have stored the date Nov. 1, 2020 in the variable fiscalYearStart and would like to output Oct. 2020. Can you please show me how to do this? I have written a function, but I get the message ERROR TypeError: fiscalYearStart.getMonth is not a function

My function:

public getLastMonth () {
    this.navService.getBeginningOfFiscalYear().subscribe((yearResp: any) => {
      if (yearResp && yearResp.success) {
        const fiscalYearStart = yearResp.fiscalYearStart;
        fiscalYearStart.setMonth(fiscalYearStart.getMonth() - 1);
        const lastMonth = new Date(fiscalYearStart);
        console.log(lastMonth);
      }
    });
  }
2 Answers

You should use Date constructor, because fiscalYearStart it's a string and doesn't have getMonth method.

const fiscalYearStart = new Date(yearResp.fiscalYearStart);
public getLastMonth () {
    this.navService.getBeginningOfFiscalYear().subscribe((yearResp: any) => {
      if (yearResp && yearResp.success) {
        const fiscalYearStart = new Date(yearResp.fiscalYearStart);
        fiscalYearStart.setMonth(fiscalYearStart.getMonth() - 1);
        const lastMonth = new Date(fiscalYearStart);
        console.log(lastMonth);
      }
    });
  }
Related