How to get Date object from json Response in typescript

Here is my json:

{ "data": [ { "comment": "3541", "datetime": "2016-01-01" } ] } 

Here is the model:

 export class Job { constructor(comment:string, datetime:Date) { this.comment = comment; this.datetime = datetime; } comment:string; datetime:Date; } 

Query:

 getJobs() { return this._http.get(jobsUrl) .map((response:Response) => <Job[]>response.json().data) } 

The problem is that after casting to Job[] I expect the datetime property to be Date , but this is a string. Should I use a Date object? What am I missing here?

+14
json angular typescript
Mar 10 '16 at 13:23
source share
2 answers

@Gunter is absolutely right. The only thing I would like to add is to actually deserialize the json object, keeping its date properties as dates, not strings (from a reference position it's not so easy to see this approach).

Here is my attempt:

 export class Helper { public static Deserialize(data: string): any { return JSON.parse(data, Helper.ReviveDateTime); } private static ReviveDateTime(key: any, value: any): any { if (typeof value === 'string') { let a = /\/Date\((\d*)\)\//.exec(value); if (a) { return new Date(+a[1]); } } return value; } } 

Here you can see this approach: JSON.parse Function in the dateReviver example.

Hope this helps.

+15
Mar 10 '16 at 18:03
source share

There is no way to find out TS / JS that this value is a date. This is a string and is treated as such. Other data types are different, but JSON does not provide any special support for the date. You need to convert it manually.

See, for example, this discussion on how to transfer and convert a date using JSON. How do I set a Microsoft JSON date?

+4
Mar 10 '16 at 13:25
source share



All Articles