首页 > 解决方案 > JSON TIME 转换成新的 Date()?

问题描述

这是我从 API 收到的。

{"$id":"1","currentDateTime":"2021-01-20T22:29-05:00","utcOffset":"-05:00:00","isDayLightSavingsTime":false,"dayOfTheWeek":"Wednesday","timeZoneName":"Eastern Standard Time","currentFileTime":132556553638838375,"ordinalDate":"2021-20","serviceResponse":null}`

它是 JSON 格式,所以我这样做了。

function setTime(data) {
let readDate = JSON.parse(JSON.stringify(data));
console.log(readDate);
let now = new Date(readDate.currentFileTime);
console.log(now);

}

我不知道如何将其转换为new Date()?

我假设我采用了对象的 currentFileTime 属性,并且我希望 Date 方法的组合能够起作用。

任何帮助,将不胜感激。谢谢你。

标签: javascript

解决方案


FILETIME将时间表示为自 1601 年 1 月 1 日以来的 100 纳秒整数(来源)。构造函数将Date时间表示为自纪元(1970 年 1 月 1 日)以来的毫秒数(来源)。

Date因此,要从a中得到一个 JS FILETIME,我们需要除以 10,000 并减去 1970 年 1 月 1 日和 1601 年 1 月 1 日之间的差,以毫秒为单位。差值为 11,644,474,854,000 毫秒:

const windowsEpoch = new Date('January 1, 1601');
const unixEpoch = new Date('January 1, 1970');
console.log(unixEpoch - windowsEpoch);

这是代码:

function filetimeToDate(filetime) {
  const epochsDiff = 11644474854000;
  return new Date((filetime / 10000) - epochsDiff);
}

function setTime(data) {
  let readDate = JSON.parse(JSON.stringify(data));
  let now = filetimeToDate(readDate.currentFileTime);
  console.log(now);
}
setTime({"$id":"1","currentDateTime":"2021-01-20T22:29-05:00","utcOffset":"-05:00:00","isDayLightSavingsTime":false,"dayOfTheWeek":"Wednesday","timeZoneName":"Eastern Standard Time","currentFileTime":132556553638838375,"ordinalDate":"2021-20","serviceResponse":null});

编辑:上面的数字和计算实际上是不准确的,因为 JS 使用双精度浮点(最多可以精确存储 2^53),但我们处理的是 64 位整数。如果精度对您很重要(最多几秒或几毫秒),您可以使用BigInts。但是,我没有使用它,因为差异并不显着,并且BigInts:a)减慢计算速度,b)还不能作为普通 JS 数字移植。


推荐阅读