How to get Date object from json Response in typescript

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

Here is my json:

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

Here is model:



        
4条回答
  •  温柔的废话
    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.

提交回复
热议问题