为什么在 javascript 中计算时差时会得到 +1 小时? [英] Why do I get +1 hour when calculating time difference in javascript?
问题描述
我试图创建一个非常简单的时差计算.只是结束时间 - 开始时间".不过我得到了 +1 小时.我怀疑这与我的时区有关,因为我是 GMT+1.
I trying to create a very simple time difference calculation. Just "endtime - starttime". I'm getting +1 hour though. I suspect it has with my timezone to do, since I'm GMT+1.
无论如何,这不应该影响差异,因为开始和结束时间都在同一时区.
Regardless, that should not affect the difference, since both start and end times are in the same timezone.
在此处检查我正在运行的示例代码:
Check my running example-code here:
http://jsfiddle.net/kaze72/Rm3f3/
$(document).ready(function() {
var tid1 = (new Date).getTime();
$("#tid").click(function() {
var nu = (new Date).getTime();
var diff = new Date(nu - tid1);
console.log(diff.getUTCHours() + ":" +
diff.getUTCMinutes() + ":" +
diff.getUTCSeconds());
console.log(diff.toLocaleTimeString());
});
})
推荐答案
您必须了解 Date
对象代表什么以及它如何存储日期.基本上每个 Date
都是围绕自 1970 年以来的毫秒数(所谓的纪元时间)的薄包装.通过从另一个日期中减去一个日期,您不会得到日期:您只会得到两者之间的毫秒数.
You must understand what Date
object represent and how it stores dates. Basically each Date
is a thin wrapper around the number of milliseconds since 1970 (so called epoch time). By subtracting one date from another you don't get a date: you just get the number of milliseconds between the two.
话虽如此,这条线没有多大意义:
That being said this line doesn't have much sense:
var diff = new Date(nu - tid1);
你真正需要的是:
var diffMillis = nu - tid1;
...然后简单地提取秒、分钟等:
...and then simply extract seconds, minutes, etc.:
var seconds = Math.floor(diffMillis / 1000);
var secondsPart = seconds % 60;
var minutes = Math.floor(seconds / 60);
var minutesPart = minutes % 60;
var hoursPart = Math.floor(minutes / 60);
//...
console.log(hoursPart + ":" + minutesPart + ":" + secondsPart);
这篇关于为什么在 javascript 中计算时差时会得到 +1 小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!