Angular2 DatePipe处理ISO 8601日期(管道'DatePipe'的无效参数'*')? [英] Angular2 DatePipe processing ISO 8601 Date (Invalid argument '*' for pipe 'DatePipe')?

查看:184
本文介绍了Angular2 DatePipe处理ISO 8601日期(管道'DatePipe'的无效参数'*')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚尝试在我的 angular2 应用中使用简单的date管道:

I've just tried to use a simple date pipe in my angular2 app:

Registered: {{user.registered | date:'shortDate'}}

我得到的错误是:

Invalid argument '2016-03-28T07:25:40.824Z' for pipe 'DatePipe' in [{{user && user.registered | date:'shortDate' }} in UserDialog@16:57]

我确实有一个在此组件和其他组件之间共享的用户模型(此处最小):

I do have a User model (minimal here) shared between this component and some others:

export class User { public registered: Date; }

我从后端获取用户数据作为JSON,它是一个ISO 8601: 2016-03-28T07:26:01.202Z .

I get the user data as JSON from backend, and it's a ISO 8601: 2016-03-28T07:26:01.202Z.

当我使用自己的自定义管道时,它可以工作(例如下面的示例).

When I use my own custom pipe, it works (example bellow).

import {Pipe, PipeTransform} from 'angular2/core';
/**
 * The default ISO Date is not parseable by ts compiler or some such.
*/
@Pipe({ name: 'betterDate' })
export class BetterDatePipe implements PipeTransform {

  transform(date: number): string {

    let d = new Date(date);
    return d.toLocaleDateString();
  }
}

名称 更好 DatePipe 显然对我来说是一个比发明人编写更好的angular2代码的双关语;)

The name, BetterDatePipe is obviously a pun at me writing better angular2 code then the inventors ;)

推荐答案

我发现两者都有优点,但是OP的代码有些局限性:它始终始终返回相同的日期格式,最终您将编写另一个Pipe仍要更改该格式.

I see merits in both, but the OP's code somewhat limiting: it always returns the same date format all the time, you're ultimately going to write another Pipe to change that format anyway.

第二种方法听起来更易于管理:但是,有些事情,管道不是您包含在@Component中的东西,您必须在app.module.ts中将其引用为导入声明:

The second method sounds a whole lot more manageable: however, a few things, the pipes isn't something you include in the @Component, you'd have to refer that in the app.module.ts as both an import statement:

import { StringToDatePipe } from './???/string-to-date.pipe'

,以及需要将其包含在@NGModule({...中,位于声明下方的页面下方.

as well as needing to include it in the @NGModule({... further down the page under declarations.

您可以在此处使用自定义管道",然后使用 Angular的日期管道

From there, you can use the Custom Pipe, and then moving onto using Angular's Date Pipe

这篇关于Angular2 DatePipe处理ISO 8601日期(管道'DatePipe'的无效参数'*')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆