I have an Angular 2 application. A service is requests data from an api that returns the results like the following:
{
\"data\":[
{\"id\":1,\"ti
I would map the string field to a date one:
getList() : Observable<SomeModel[]> {
return this._http.get(this._getListUrl).map(this.extractData);
}
private extractData(res: Response) {
var data = res.json().data || [];
data.forEach((d) => {
d.timestamp = new Date(d.timestamp);
});
return data;
}
Try out my example if its work for you. And here is the docs for Date and Pipe.
<span>Date : {{announcement.createdAt | date:'EEE, d MMM,y'}}</span>
<span>Time : {{announcement.createdAt | date:'shortTime'}}</span>
Output :
Date : Tue, 20 Dec,2016
Time : 2:22 PM
JSON does not provide any date specification, so it is entirely up to how it is serialized/deserialized.
You could use reviver
parameter of JSON.parse
:
this._http.get(this._getListUrl).map(res => JSON.parse(res.text(), this.reviver));
reviver(key, value):any
{
if('timestamp' === key){
//you can use any de-serialization algorithm here
return new Date(value);
}
return value;
}
The date
pipe only accepts Date
values not string values.
See How to get Date object from json Response in typescript for how to convert dates in JSON.
Alternatively you can create your own string-to-date conversion pipe
@Pipe({name: 'toDate'})
export class StringToDate implements PipeTransform {
transform(value, [exponent]) : number {
if(value) {
return new Date(value);
}
}
}
and then use it like
{{item.timestamp |toDate | date:'short'}}
Hint: don't forget to add the pipe to pipes: [StringToDate]
on the @Component(...)
decorater where you want to use it.
See also