Ced
Ced

Reputation: 1301

Typescript mapping Json to interface parsing date

I'm mapping my JSON responses from the Server side code into an Interface, in this way;

objectFromJson: IMyObject = <IMyObject>jsonData;

The problem is, that the Json contains a Date, is there a way to automatic cast the date to an real Typescript Date without something like this:

new Date(parseInt(incident["CreatedOn"].substr(6)));

Upvotes: 6

Views: 2132

Answers (1)

basarat
basarat

Reputation: 276363

that the Json contains a Date, is there a way to automatic cast the date to an real Typescript Date without something like this

Your json seems to create date as a number. BAD IDEA. Reason:

  • how about dates before 1970
  • it is unreliable based on time zones

Prefer you return dates as strings. More API recommendations : https://github.com/interagent/http-api-design

If all you have is it returned as number than what you have is okay. Else if you have dates in a JavaScript recommended format e.g. 2012-01-01T12:00:00Z you would do var date = new Date('2012-01-01T12:00:00Z')

Upvotes: 3

Related Questions