【发布时间】:2021-03-10 18:31:37
【问题描述】:
我正在尝试验证在打字稿中使用时刻的日期。但它给出了错误的输出。虽然我提供了一组不同的日期格式并根据这些日期格式给出了一个日期,但验证总是返回 false。
HTML
`
<p-calendar [ngModel]="author.birthDate | momentToDateString"
[inline]="false" [required]="true"
name="inpBirthDate" #birthDate="ngModel" [showIcon]="true"
[maxDate]="maxDate" (ngModelChange)="author.birthDate = $event"
[dateFormat]="dateFormat"
(onInput)="author.birthDate = dateTimeUpdate($event)"
[monthNavigator]="appConsts.calendarSettings.monthNavigator"
[yearNavigator]="appConsts.calendarSettings.yearNavigator"
[yearRange]="appConsts.calendarSettings.yearRange">
</p-calendar>
`
TS
`
dateTimeUpdate(event, isTime = false) {
const expectedFormat = isTime ?
this.appConsts.expectedDateTimeFormat :
this.appConsts.expectedDateFormat;
const date = event.target.value;
if (
event !== null && event !== undefined &&
date !== null &&date !== undefined && date !== ''
) {
let formatedDate = moment(date, expectedFormat, true);
if (formatedDate.isValid()) {
return formatedDate.toDate();
}
}
return '';
}
`
expectedDateFormat
`
['dd-MM-YY', 'd-MM-YY']
`
expectedDateTimeFormat
`
['dd-MM-YY, h:mm:ss a', 'd-MM-YY, h:mm:ss a']
`
由于函数参数isTime为false,那么expectedDateFormat会被选中,虽然我给了10-03-21这样的日期,但它返回false
【问题讨论】:
标签: angularjs typescript momentjs