如何在 Angular 5 应用程序中使用 DatePipe 验证日期?

How to validate date using DatePipe in Angular 5 app?

我有 bsDatepicker 和 bsConfig,我正在尝试验证它,以确保它的格式正确。问题是 bsDatepicker 以不同的格式创建日期,所以我无法验证它。

日期字符串是:

Mon Apr 01 2019 19:05:36 GMT+1100 (Australian Eastern Daylight Time)

我正在尝试使用 DatePipe 对其进行转换,例如:

dateStr = this.datepipe.transform(date.toDateString(), 'MM/dd/yyyy');

我得到的是空的。预期结果为 04/01/2019。 知道为什么 datepipe 无法转换吗? 谢谢

date.toDateString 你缺少括号 date.toDateString()

不知道为什么 toDateString() 到那个时候。您可以像这样解析日期

this.dateStr = this.datePipe.transform(new Date(date.toDateString()) ,'MM/dd/yyyy');

演示:https://stackblitz.com/edit/angular-datepipe-in-component-test

可以使用 Datepipe

将打字稿中的日期转换为这种格式'yyyy-MM-dd'
import { DatePipe } from '@angular/common'

constructor(public datepipe: DatePipe){}

myFunction(){
 this.date=new Date();
 let latest_date =this.datepipe.transform(this.date, 'mm-dd-yyyy');
}

然后将 Datepipe 添加到 app.module.ts 的 'providers' 数组中。像这样:

import { DatePipe } from '@angular/common'

providers: [DatePipe]
private static datePipeEn: DatePipe = new DatePipe('en-US');

解决了我的问题,希望对遇到类似问题的人有所帮助!