typescript 如何在angular 9中从当前日期中减去一天[重复]

nhaq1z21  于 2023-04-07  发布在  TypeScript
关注(0)|答案(2)|浏览(174)

此问题已在此处有答案

How to get the previous date in angular?(3个答案)
2年前关闭.

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

在上面的代码中,我得到了当前日期。要求是从当前日期减去一天意味着我可以得到昨天。

eyh26e7m

eyh26e7m1#

要输出昨天的日期,请使用以下代码块。

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

dxpyg8gm2#

这个函数将任意数量的天数加到传递的Date对象上。通过传递-1,我们实际上减去了一天。

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

顺便说一句,尽量不要在组件中使用管道,并参考How to format a JavaScript date了解如何格式化日期的更多细节。

相关问题