【发布时间】:2022-01-29 12:00:18
【问题描述】:
【问题讨论】:
-
所以这似乎是一种自定义时间格式?你有它作为字符串还是 json?
-
它不是我们在 firebase 中保存为时间戳的原因
标签: javascript timestamp
【问题讨论】:
标签: javascript timestamp
当您获取文档时,'timestamp' 字段的类型为Timestamp,您可以使用seconds 属性和当前时间戳来计算差异,如下所示:
const snap = await getDoc(docRef);
const timeDiff = Date.now() - snap.data()?.time.seconds * 1000;
console.log(`Time Difference: ${timeDiff} ms`)
【讨论】:
这其实很容易实现。最重要的是要知道函数 Date.now() 会返回自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数。
获取时间戳之间的持续时间类似于“结束 - 开始 = 持续时间”。
这是一个代码示例:
// collect the first timestamp
const beginTimestamp = Date.now()
// here comes a for loop to consume some time, otherwise you will get 0 milliseconds
for (var i=0; i<10000; i++) {
"Some kind of string".split("").reverse().join("")
}
// collect the second timestamp
const endTimestamp = Date.now()
// subtract the first from the second timestamp tells you the milliseconds in between of both timestamps
console.log("Duration in milliseconds:", endTimestamp - beginTimestamp)
【讨论】: