Angular2 DatePipe processing ISO 8601 Date (Invalid argument '*' for pipe 'DatePipe')?

杀马特。学长 韩版系。学妹 提交于 2019-12-06 16:33:58

Instead of re-implementing the pipe, you may write an intermediary one, transforming the component's string value into date first:

string-to-date.pipe.ts:

import {Pipe, PipeTransform} from '@angular/core';
/**
 * Pipe to transform a string to a date
 */
@Pipe({name: 'stringToDate'})
export class StringToDatePipe implements PipeTransform {
    /**
     * Constructor
     */
    constructor() {
    }
    /**
     * Transform a date that is passed as string into a date
     * @param value The date passed as string
     * @returns {Date} The Date object
     */
    transform(value: string): Date {
        return new Date(value);
    }
}

Component

import {StringToDatePipe} from './string-to-date.pipe';
@Component({
    ...
    pipes: [StringToDatePipe],
    ...
})

Template

Registered: {{user.registered | stringToDate | date:'shortDate'}}
Günter Zöchbauer

The argument is obviously a string, not a Date. You need to convert it to Date before passing it to the pipe. JSON doesn't support type Date.

user.registered = new Date(json.registered);

or similar depending on how you get the user object.

See also Converting string to date in js

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.

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'

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!