【发布时间】:2019-10-12 10:56:38
【问题描述】:
调用返回 JSON 的 REST 服务时,如何格式化日期以便自动将其转换为打字稿 Date 对象?
调用 REST 调用的结果是这样的消息:
{"id":3796,...,"startTempValue":"2019-05-26T19:39:01Z"}
我也试过这种 ISO 格式:
{"id":3796,...,"startTempValue":"2019-05-26T19:39:01.000Z"}
模型对象是:
export class Settings {
public id: number;
public shortName;
public description: string;
public value: string;
public possibleValues: string;
public startTempValue: Date;
}
startTempValue 的结果是一个字符串... ?!我希望 startTempValue 是一个 Date 对象。
当然,我可以手动将 Date 字符串转换为 Date 对象。因此,在接收 REST 服务结果时执行类似于以下代码的操作。 但应该有更好的方法。 另一种选择是在服务器上将其转换为纪元(毫秒)。这是可能的,但这个“字符串”变体仍然更具可读性。
if ( this.settings[i].startTempValue !== undefined &&
this.settings[i].startTempValue !== null) {
this.settings[i].startTempValue = new Date(this.settings[i].startTempValue);
} else {
this.settings[i].startTempValue = null;
}
【问题讨论】:
标签: json typescript rest