How to get Date object from json Response in typescript

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

Here is my json:

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

Here is model:



        
4条回答
  •  野性不改
    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 } ] }
    

提交回复
热议问题