I recently attempted to implement a basic date
pipe in my angular2 application:
Registered: {{user.registered | date:'shortDate'}}
However, I encountered the following error:
Invalid argument '2016-03-28T07:25:40.824Z' for pipe 'DatePipe' in [{{user && user.registered | date:'shortDate' }} in UserDialog@16:57]
In order to resolve this issue, I defined a minimal User
model which is shared among various components:
export class User { public registered: Date; }
The backend provides the user data in ISO 8601 format: 2016-03-28T07:26:01.202Z
.
To make it work, I created a custom pipe as shown below:
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();
}
}
The tongue-in-cheek name, BetterDatePipe, signifies my attempt to improve upon angular2 coding practices.