javascript - 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 方法的组合能够起作用。
任何帮助,将不胜感激。谢谢你。
解决方案
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 位整数。如果精度对您很重要(最多几秒或几毫秒),您可以使用BigInt
s。但是,我没有使用它,因为差异并不显着,并且BigInt
s:a)减慢计算速度,b)还不能作为普通 JS 数字移植。
推荐阅读
- java - Java:A 类中 B 类的实例,其中 B 类使用 A 类中声明的变量
- java - 如何垂直显示用户输入的字符串与字符串中的字符一样多
- python - 黑色格式化程序 - 忽略特定的多行代码
- video-streaming - 来自 IP 摄像机的“实时采样”(非流式传输)
- reactjs - 将页面路由到组件中:React
- outlook - 如何使用 C# 在我有写权限的其他用户日历中创建一个 evet?
- c - 桶排序段错误
- agda - Agda Data.Bool 求解器的使用
- angular - Angular、打字稿、谷歌图表 - 类型(日期|数字)[][] 不可分配给类型数组
> - c++ - C++ - 使用 std::list,如何打印对象私有成员的链表?