区域设置日期Angular 8无法转换



在我的app.module.ts中,我添加了以下代码:

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:"无法转换";2021年9月22日上午11:14:38;转换为管道"DatePipe"的日期

如果我试图在运行时用jun替换giu,我不会得到任何错误,所以问题应该是它试图使用英语而不是意大利语。我想它没有读取我在app.module.ts中定义的内容,如何修复?

方法toDate用于将字符串转换为日期管道引擎盖下的Date。查看它的源代码,我惊讶地发现我们在模块配置中提供的区域设置没有被考虑在内。它检查:

  • 如果字符串实际上是一个数字(不是您的情况(
  • 如果使用的字符串是没有时间的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构造函数处理的格式。

最新更新