如何在打字稿中将日期转换为字符串格式 yyyy-mm-dd

Shi*_*iny 2 date typescript angular

如何在打字稿中将日期转换为字符串格式yyyy-mm-dd

现在我得到的日期为2017 年 3 月 24 日星期五 00:00:00 GMT-0400(东部夏令时)

我只需要格式为“2017-03-24”的日期, 没有任何时区和时区转换

wen*_*jun 5

假设您使用的是 Angular,您可以将 DatePipe 或 FormatDate 导入到您的 component.ts 中来处理。您可以阅读有关可以作为参数传递的各种日期/时间格式的更多信息。

1) 日期管道:

import { DatePipe } from '@angular/common';

export class SampleComponent implements OnInit {   

constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记将 DatePipe 添加到您的模块中的提供程序。

providers: [DatePipe]
Run Code Online (Sandbox Code Playgroud)

2)格式日期:

import { formatDate } from '@angular/common';

export class SampleComponent implements OnInit {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}
Run Code Online (Sandbox Code Playgroud)