【问题标题】:Find difference between two unix timestamps that are within 24 hours in TypeScript and Node在 TypeScript 和 Node 中查找 24 小时内的两个 unix 时间戳之间的差异
【发布时间】:2021-10-01 19:24:26
【问题描述】:

我有两个示例 unix 时间戳,我试图找出以小时/分钟/秒为单位的差异。一个是来自 TypeScript 的当前时间,一个是 24 小时后的过期时间。我只想打印出到期前的剩余时间。如何在 TypeScript 和 Node 中解决这个问题?

current_time = 1633115367891
exp_time = 01633201203

【问题讨论】:

  • 我认为你有两个不同的时间戳,一个是毫秒,另一个是 unix 时间戳。
  • 哦,好吧,我从一个名为 JWT(json Web 令牌)的包中获取过期时间,unixtimestamp.com 确实显示了它们的正确时间。

标签: javascript node.js typescript unix-timestamp


【解决方案1】:

您可以将 unix 时间戳转换为毫秒时间戳并获取它们的增量。然后将增量转换为hh:mm:ss 格式。

const current_time = 1633115367891,
  exp_time = 1633201203,
  diff = (exp_time * 1000) - current_time,
  formatTime = (ms) => {
    const seconds = Math.floor((ms / 1000) % 60);
    const minutes = Math.floor((ms / 1000 / 60) % 60);
    const hours = Math.floor((ms / 1000 / 3600) % 24);
    return [hours, minutes, seconds].map(v => String(v).padStart(2,0)).join(':');
  }
console.log(formatTime(diff));

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2014-05-04
    • 2013-03-22
    • 1970-01-01
    • 2017-12-21
    相关资源
    最近更新 更多