【问题标题】:How to calculate difference between saved timestamp and current time如何计算保存的时间戳和当前时间之间的差异
【发布时间】:2022-01-29 12:00:18
【问题描述】:

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

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

希望任何人都可以提供帮助。

【问题讨论】:

  • 所以这似乎是一种自定义时间格式?你有它作为字符串还是 json?
  • 它不是我们在 firebase 中保存为时间戳的原因

标签: javascript timestamp


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    这其实很容易实现。最重要的是要知道函数 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 2020-05-13
      相关资源
      最近更新 更多