0
ngOnInit(): void {
    this.currentDate = new Date();
    this.date = this.datePipe.transform(this.currentDate, 'y-MM-dd');
    this.currentDate = this.date;
}

In the above code Im getting current date. The requirement is from this current date need to subtract a day means i can get yesterday.

Ganesh babu
  • 19
  • 1
  • 6
  • check this link https://stackoverflow.com/questions/47260283/how-to-get-the-previous-date-in-angular/47260315#47260315 – Ganesh Rana Jul 16 '20 at 10:34

2 Answers2

4

To output the date of yesterday, use the following block of code.

export class DateComponent implements OnInit{
    datePipe = new DatePipe('en');
    public today?: Date;
    public yesterday?: string | null;

  ngOnInit(){
    // The following output tests the method 'getYesterday()'.
    console.log(this.getYesterday());
  }

  getYesterday(){
    this.today = new Date();
    this.today.setDate(this.today.getDate() - 1);
    // The following returns the formatted date.
    return this.yesterday = this.datePipe.transform(this.today, 'dd-MM-y');
  }
}
Graham John
  • 170
  • 12
surendra kumar
  • 1,686
  • 11
  • 15
1

This function adds any amount of days to the passed Date object. By passing -1 we effectiviely subtract a day.

function addDays(a_oDate: Date, days: number): Date {
        a_oDate.setDate(a_oDate.getDate() + days);
        return a_oDate;
    }
    
    console.log(addDays(new Date(), - 1));

As a sidenote, try not to use pipes in your components, and refer to How to format a JavaScript date on more details on how to format your date.