How to get Date object from json Response in typescript

前端 未结 4 2077
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 11:18

Here is my json:

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

Here is model:



        
相关标签:
4条回答
  • 2020-11-28 11:42

    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?

    0 讨论(0)
  • 2020-11-28 11:47

    @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.

    0 讨论(0)
  • 2020-11-28 11:48

    You can achieve it using 2 properties: a string property (say dateStr) for passing the date and a Date property (say dateVal) to hold the data object after conversion.

    Then in your constructor, you can simply do something like dateVal = new Date(dateStr).

    0 讨论(0)
  • 2020-11-28 11:55

    If usage of custom TypeScript transformer is possible, ts-transformer-dates could be used:

    import { toDates } from 'ts-transformer-dates';
    
    const value = {
      "data": [
        {
          "comment": "3541",
          "datetime": "2016-01-01"
        }
      ]
    };
    
    export class Job {
        constructor(comment:string, datetime:Date) {
            this.comment = comment;
            this.datetime = datetime;
        }
    
        comment:string;
        datetime:Date;
    }
    
    console.log(toDates<{data:Job[]}>(value));
    

    Output:

    { data: [ { comment: '3541', datetime: 2016-01-01T00:00:00.000Z } ] }
    
    0 讨论(0)
提交回复
热议问题