How to get the previous date in angular?

Viewed 19921

Please help me getting the previous dates in angular 4.

currentdate: Date;
this.currentdate = new Date();
console.log(this.datePipe.transform(this.currentdate, 'yyyy-MM-dd'));

Here I got the date as 2017-11-13.

Now I need to get 2 days before date..

3 Answers

Try this

let dte = new Date();
dte.setDate(dte.getDate() - 2);
console.log(dte.toString());

I am not sure if the year -1 thing is always valid since February 29th issue. I think more accurate way is that

let aDate = new Date();
aDate.setDate(aDate.getDate() - numberOfDaysBefore);

replace 365 with number of days you want. Thank you!

The accepted answer is correct for javascript, this works in Angular:

export class MyClass implements OnInit {
  // This gives you todays date.
  private dateToday: Date = new Date();
  // This also gives you todays date if you don't alter it on init.
  private dateYesterday: Date = new Date();

  constructor() { }

  ngOnInit() {
    // Alters the date
    this.dateYesterday = new Date(this.dateYesterday.setDate(this.dateYesterday.getDate() - 1));
  }

}

Related