1

我正在尝试创建某种计时器。所以我有一些时间戳来标记完成时间,当脚本开始时我得到当前时间戳,然后我每秒增加 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;
4

4 回答 4

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;
}
于 2013-08-14T19:46:17.283 回答
4

使用 JavaScriptDate对象将您的时间戳转换为日期和时间:

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/

于 2013-08-14T19:48:30.123 回答
3

我认为您需要 math.floor 而不是 match.ceil。任何小于 3600 秒的时间都不是一个小时。

您可以使用modulo( %) 从剩余的分钟数中过滤出小时数(秒数相同)。

hours_diff = Math.floor(diff/3600);
mins_diff = Math.floor((diff % 3600)/60)
secs_diff = diff%60;
于 2013-08-14T19:44:44.523 回答
1

创建一个以毫秒为单位的日期对象:

 d = new Date (seconds * 1000);

现在 UTC 小时、分钟和秒符合您的要求

 console.log (d.getUTCHours () ,d.getUTCMinutes (), d.getUTCSeconds ()) 
于 2013-08-14T19:56:28.687 回答