gpt4 book ai didi

javascript - 我怎样才能找到 HH :MM:SS difference between two UNIX timestamps?

转载 作者:行者123 更新时间:2023-11-28 11:12:44 25 4
gpt4 key购买 nike

我正在尝试创建某种计时器。所以我有一些时间戳来标记完成时间,并且在脚本启动时获取当前时间戳,然后每秒将其增加 1。我需要以某种方式每秒计算这两者之间的差异,并以小时:分钟:秒的格式显示它。

这是我当前的解决方案,但显然它不起作用。 end_timecur_time 是时间戳:

diff = end_time - cur_time;
hours_diff = Math.ceil(diff/3600)
mins_diff = Math.ceil((diff-hours_diff)/60)
secs_diff = diff - hours_diff*3600 - mins_diff*60;

最佳答案

您需要从较小的单位开始并逐步提高:

diff = Math.floor(diff / 1000);
var secs_diff = diff % 60;
diff = Math.floor(diff / 60);
var mins_diff = diff % 60;
diff = Math.floor(diff / 60);
var hours_diff = diff % 24;
diff = Math.floor(diff / 24);
// and so on, with the next divisor being 7
// for days by week, for example.

在每一步中,您都会执行除法和余数运算。余数为您提供当前单位。您除以的金额(和余数)就是下一个较大时间单位中的单位数。

最初除以 1000 假设您的时间戳以毫秒为单位。如果它们在几秒钟内,你就不需要它。

您可以通过将除数和标签存储在数组中来使事情变得更整洁:

function timeDiff( tstart, tend ) {
var diff = Math.floor((tend - tstart) / 1000), units = [
{ d: 60, l: "seconds" },
{ d: 60, l: "minutes" },
{ d: 24, l: "hours" },
{ d: 7, l: "days" }
];

var s = '';
for (var i = 0; i < units.length; ++i) {
s = (diff % units[i].d) + " " + units[i].l + " " + s;
diff = Math.floor(diff / units[i].d);
}
return s;
}

关于javascript - 我怎样才能找到 HH :MM:SS difference between two UNIX timestamps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18240806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com