我正在以这种方式将来自服务器端代码的 JSON 响应映射到接口(interface)中;
objectFromJson: IMyObject = <IMyObject>jsonData;
问题是,Json 包含一个日期,有没有办法自动将日期转换为真正的 Typescript 日期,而无需像这样:
new Date(parseInt(incident["CreatedOn"].substr(6)));
最佳答案
that the Json contains a Date, is there a way to automatic cast the date to an real Typescript Date without something like this
您的 json 似乎将日期创建为 number
。馊主意。原因:
- 1970 年之前的日期怎么样
- 根据时区不可靠
更喜欢将日期作为字符串返回。更多 API 推荐:https://github.com/interagent/http-api-design
如果您所拥有的只是以数字形式返回,那么您所拥有的就可以了。否则,如果您有 JavaScript 推荐格式的日期,例如2012-01-01T12:00:00Z
你会做 var date = new Date('2012-01-01T12:00:00Z')
关于json - Typescript映射Json到接口(interface)解析日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27917676/