sasi
sasi

Reputation: 135

How to get the previous date in angular?

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..

Upvotes: 9

Views: 28545

Answers (3)

ASomN
ASomN

Reputation: 198

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));
  }

}

Upvotes: 1

Rashmi Prbhath
Rashmi Prbhath

Reputation: 117

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!

Upvotes: 1

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

Try this

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

Upvotes: 18

Related Questions