如何以角度2获取YYYY-MM-DD格式的日期

Sta*_*y J 4 javascript date angular2-services angular

我希望以下列格式获取日期:YYYY-MM-DD.

我基于这个问题在Angular2中写了一个日期服务: 如何在JavaScript中获取当前日期?.

我想检查它是否是正确的实现,或者是否有更好的方法来实现目标.

import { Injectable } from '@angular/core';

@Injectable()
export class DateService {
private currentDate = new Date();

    getCurrentDateInApiFormat(): string{
        let day:any = this.currentDate.getDate();
        let month:any = this.currentDate.getMonth() + 1;
        let year:any = this.currentDate.getFullYear();
        let dateInApiFormat: string;

        if(day<10){
           day = '0' + day.toString();
        }
        if(month<10){
            month = '0' + month.toString();
        }
        dateInApiFormat = day + '-' + month + '-' + year.toString();
        return dateInApiFormat;
    }
}
Run Code Online (Sandbox Code Playgroud)

Saj*_*ran 6

你可以简单地使用 Date Pipe

 <p>The time is {{currentDate | date:'yyyy-MM-dd'}}</p>
Run Code Online (Sandbox Code Playgroud)

在TS

export class App {

 currentDate: number = Date.now();

}
Run Code Online (Sandbox Code Playgroud)

DEMO