我正在尝试创建某种计时器的东西。所以我有一些时间戳来标记完成时间,我得到脚本启动时的当前时间戳,然后我每秒增加1。我需要以某种方式计算这两者之间的差异,并以Hours : Minutes : Seconds
的格式显示它。
这是我目前的解决方案,但显然它不起作用。 end_time
和cur_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;
答案 0 :(得分:5)
您需要从较小的单位开始并进行处理:
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;
}
答案 1 :(得分:3)
我认为你需要math.floor而不是match.ceil。任何小于3600秒的东西还不到一个小时。
您可以使用modulo
(%
)过滤掉剩余分钟的小时数(同样的秒数)。
hours_diff = Math.floor(diff/3600);
mins_diff = Math.floor((diff % 3600)/60)
secs_diff = diff%60;
答案 2 :(得分:2)
使用JavaScript Date
对象将您的时间戳转换为日期&amp;时间:
var timeDifference = end_time - cur_time;
var differenceDate = new Date(timeDifference * 1000);
var diffHours = differenceDate.getUTCHours();
var diffMinutes = differenceDate.getUTCMinutes();
var diffSeconds = differenceDate.getUTCSeconds();
然后以H:M:S格式获得可读时间:
var readableDifference = diffHours + ':' + diffMinutes + ':' + diffSeconds;
你必须乘以1000
得到毫秒的差异(这是Date
的构造函数所期望的)。
Unix时间戳表示自1970/01/01以来以秒为单位的时间。
快速JSFiddle演示:http://jsfiddle.net/WaZQt/
答案 3 :(得分:1)
创建一个具有毫秒数的日期对象:
d = new Date (seconds * 1000);
现在,UTC小时,分钟和秒钟符合您的要求
console.log (d.getUTCHours () ,d.getUTCMinutes (), d.getUTCSeconds ())