英文:
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) => {
// absolute value added incase you just want the diff but don't care which came first
return (Math.abs(timestampB - timestampA)) / 1000
}
const res = diffInSeconds(1673256249000, 1673256240000)
console.log(res) // 9
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论