获取两个 Epoch 时间之间的时间差(以秒为单位),JavaScript

huangapple go评论64阅读模式
英文:

Get time difference in seconds, between 2 Epoch times, Javascript

问题

我有2个Epoch时间,例如 1673252582, 1673253317

现在我正在尝试使用date-fns来计算这两者之间的秒数差,如下所示: differenceInSeconds(1673252582, 1673253317)

但这给我返回了**-0**作为结果。

请帮忙。

英文:

I have 2 Epoch times, e.g. 1673252582, 1673253317

Now i am trying to calculate Difference in seconds between these two using date-fns: differenceInSeconds(1673252582, 1673253317).

But this is giving me -0 as result.

Please help.

答案1

得分: 1

你可以通过从一个时间戳减去另一个时间戳来计算差值。

如果你需要以秒为单位,而当前输入是以毫秒为单位的,你需要通过除以1000来将毫秒转换为秒。

例如:

const diffInSeconds = (timestampA, timestampB) => {
  // 为了只获取差值但不关心哪个时间戳较大,添加绝对值
  return (Math.abs(timestampB - timestampA)) / 1000
}

const res = diffInSeconds(1673256249000, 1673256240000)
console.log(res) // 9
英文:

You can calculate the diff by subtracting one timestamp from the other.

If you need it in seconds and current input is in milliseconds, you will need to convert milliseconds to seconds by dividing by 1000.

for example:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const diffInSeconds = (timestampA, timestampB) =&gt; {
  //  absolute value added incase you just want the diff but don&#39;t care which came first
  return (Math.abs(timestampB - timestampA)) / 1000
}

const res = diffInSeconds(1673256249000, 1673256240000)
console.log(res) // 9

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月9日 16:40:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定