8

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

Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
sasi
  • 125
  • 1
  • 1
  • 5
  • Possible duplicate of https://stackoverflow.com/questions/16401804/how-to-get-the-day-before-a-date-in-javascript – Jan B. Nov 13 '17 at 08:56
  • 1
    Possible duplicate of [How to get "the day before a date" in javascript?](https://stackoverflow.com/questions/16401804/how-to-get-the-day-before-a-date-in-javascript) – Sangwin Gawande Nov 13 '17 at 09:58

3 Answers3

17

Try this

let dte = new Date();
dte.setDate(dte.getDate() - 2);
console.log(dte.toString());
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
  • 1
    It give you just a number, what if we would like to get full date of yesterday ? – Arash Apr 17 '19 at 14:46
  • 1
    @Arash what's your problem?? Did you try to run it on your machine?? It gives `Tue Apr 16 2019 10:50:36 GMT+0530 (India Standard Time)` as output. Please make sure you know what's the output then only down vote any answer. Or if needed ask your seperate question. – Saurabh Agrawal Apr 18 '19 at 05:22
1

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!

1

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

}

ASomN
  • 189
  • 7