Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Date object from json Response in typescript

Here is my json:

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

Here is 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)
}

Problem is that after casting to Job[] i expect datetimeproperty to be Date but it is string. Shouldn't it cast to Date object? What am i missing here?

like image 978
Vladimir Nani Avatar asked Mar 10 '16 13:03

Vladimir Nani


2 Answers

@Gunter is absolutely correct. The only thing I would like to add is actually how to deserialize json object keeping its date properties as dates and not strings (from the referenced post its not that 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;
    }
}

You can see this approach for example here: JSON.parse Function in the dateReviver example.

Hope this helps.

like image 57
Amid Avatar answered Oct 15 '22 11:10

Amid


There is no way to know for TS/JS that this value is a date. It's a string and treated as such. Other data types are distinguishable but JSON doesn't provide any special support for date. You need to convert it manually.

See for example this discussion how to transport and convert a date using JSON How do I format a Microsoft JSON date?

like image 9
Günter Zöchbauer Avatar answered Oct 15 '22 11:10

Günter Zöchbauer