问题描述
import { NgModule,LOCALE_ID } from '@angular/core';
import it from '@angular/common/locales/it';
import { registerLocaleData } from '@angular/common';
registerLocaleData(it);
//inside here I got all the necessary imports that I will not write here to avoid confusion
@NgModule({
declarations: [
],imports: [
],providers: [{ provide: LOCALE_ID,useValue: "it-IT" }],bootstrap: []
})
在我的 html 里面
<dd *ngIf="rec.DATECREATE" class="col-sm-8">{{rec.DATECREATE | date:'dd/MM/yyyy hh:mm:ss'}}</dd>
我收到此错误
错误:InvalidPipeArgument:“无法将“giu 22,2021 11:14:38 AM”转换为管道“DatePipe”的日期
如果我尝试在运行时用 jun 替换 giu,我不会收到任何错误,所以问题应该是它尝试使用英语而不是意大利语。 我认为它没有读取我在 app.module.ts 中定义的内容,如何解决?
解决方法
方法 toDate
用于将字符串转换为日期管道下的 Date
。查看 its source code 我很惊讶地发现我们在模块配置中提供的语言环境没有被考虑在内。它检查:
- 如果一个字符串实际上是一个数字(不是你的情况)
- 如果使用的字符串是没有时间的 ISO 格式(不是你的情况)
- 如果使用的字符串是带时间的 ISO 格式(不是您的情况)
- 回退到构造函数
const date = new Date(value as any);
if (!isDate(date)) {
throw new Error(`Unable to convert "${value}" into a date`);
}
return date;
因此,由我们的开发人员将日期从特定于位置的日期转换为 ISO、数字或我们确定将由 Date
构造函数处理的格式。