【问题标题】:Component.html:151 ERROR Error: InvalidPipeArgument: 'Unable to convert “14-05-2021” into a date' for pipe 'DatePipe'Component.html:151 错误错误:InvalidPipeArgument:'无法将“14-05-2021”转换为管道'DatePipe'的日期'
【发布时间】:2021-05-14 10:13:13
【问题描述】:

我收到来自后端 LastDate 的回复。我将此绑定到我的 ngModel 并显示在 Grid 中,但在控制台中我收到此错误

这是对应的代码

<ngx-datatable-column name="Last Date" prop="LastDate">
  <ng-template let-row="row" ngx-datatable-cell-template>
    {{row.LastDate| date: 'dd-MM-yyyy'}}
  </ng-template>
</ngx-datatable-column>

【问题讨论】:

    标签: javascript angular typescript date-pipe


    【解决方案1】:

    日期 (String) "14-05-2021" 会被 Javascript 错误解释。它接受格式为“MM-DD-YYYY”的日期,而您的输入格式为“DD-MM-YYYY”。快速解决方法是在将字符串发送到date 管道之前重新格式化字符串。

    控制器 (*.ts)

    backendFetch().subscribe({
      next: (res: any) => {
        const s = res.LastDate.split("-");
        this.row = {
          ...res,
          LastDate: `${s[1]}-${s[0]}-${s[2]}`;
        }
      },
      error: (error: any) => { }
    );
    

    这样,row 对象的LastDate 属性被调整为预期格式“MM-DD-YYYY”。

    显然,使用Array#split 进行转换是微不足道的。我确信其他人可以提出更好的解决方案(例如,使用 RegEx)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2021-12-25
      相关资源
      最近更新 更多