[英]How to validate date using DatePipe in Angular 5 app?
I have bsDatepicker with bsConfig and I'm trying to validate it, to make sure it is with the right format. 我有bsDatepicker与bsConfig,我正在尝试验证它,以确保它具有正确的格式。 The problem is that bsDatepicker create a date in a different format so I can't validate it.
问题是bsDatepicker以不同的格式创建日期,因此我无法对其进行验证。
The date string is: 日期字符串是:
Mon Apr 01 2019 19:05:36 GMT+1100 (Australian Eastern Daylight Time)
I'm trying to transform it using DatePipe like: 我正在尝试使用DatePipe转换它,如:
dateStr = this.datepipe.transform(date.toDateString(), 'MM/dd/yyyy');
What I'm getting is null. 我得到的是null。 The expected result will be 04/01/2019.
预期结果将是04/01/2019。 Any idea why the datepipe failed to transform?
知道为什么日期管道无法转换? Thanks.
谢谢。
date.toDateString你缺少括号date.toDateString()
Not sure why toDateString()
to that time. 不确定为什么
toDateString()
到那个时候。 You can parse to Date like this 您可以像这样解析日期
this.dateStr = this.datePipe.transform(new Date(date.toDateString()) ,'MM/dd/yyyy');
Demo: https://stackblitz.com/edit/angular-datepipe-in-component-test 演示: https : //stackblitz.com/edit/angular-datepipe-in-component-test
The date can be converted in typescript to this format 'yyyy-MM-dd' by using Datepipe 可以使用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');
}
and just add Datepipe in 'providers' array of app.module.ts. 并在app.module.ts的'providers'数组中添加Datepipe。 Like this:
像这样:
import { DatePipe } from '@angular/common'
providers: [DatePipe]
private static datePipeEn: DatePipe = new DatePipe('en-US');
解决了我的问题,我希望它会帮助有类似问题的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.