如何计算保存的时间戳和当前时间之间的差异

How to calculate difference between saved timestamp and current time

我以这种格式保存了时间戳。

所以我现在要做的是在JavaScript函数中计算当前时间和保存的时间戳之间的差异。但是我不知道该怎么做。

希望大家帮帮忙。

这其实很容易实现。最重要的是要知道函数 Date.now() returns 你是自 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)

当您获取文档时,'timestamp' 字段将是 Timestamp 类型,您可以使用 seconds 属性 和当前时间戳来计算差异,如下所示:

const snap = await getDoc(docRef);
const timeDiff = Date.now() - snap.data()?.time.seconds * 1000;

console.log(`Time Difference: ${timeDiff} ms`)