您需要从较小的单位开始并进行处理:
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;
}