javascript 日期()与日期()。getTime()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15401211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date() vs Date().getTime()
提问by Antony
What is the difference between using new Date()
and new Date().getTime()
when subtracting two timestamps? (test script on jsFiddle)
使用new Date()
和new Date().getTime()
减去两个时间戳有什么区别?(jsFiddle 上的测试脚本)
Both of the following gives the same results:
以下两个给出相同的结果:
var prev1 = new Date();
setTimeout(function() {
var curr1 = new Date();
var diff1 = curr1 - prev1;
}, 500);
var prev2 = new Date().getTime();
setTimeout(function() {
var curr2 = new Date().getTime();
var diff2 = curr2 - prev2;
}, 500);
Is there a reason I should prefer one over another?
有什么理由让我更喜欢一个吗?
回答by Jamund Ferguson
I get that it wasn't in your questions, but you may want to consider Date.now()
which is fastest because you don't need to instantiate a new Date
object, see the following for a comparison of the different versions:
http://jsperf.com/date-now-vs-new-date-gettime/8
我知道这不在您的问题中,但您可能想考虑Date.now()
哪个最快,因为您不需要实例化新Date
对象,请参阅以下内容以比较不同版本:http:
//jsperf.com /date-now-vs-new-date-gettime/8
The above link shows using new Date()
is faster than (new Date()).getTime()
, but that Date.now()
is faster than them all.
上面的链接显示 usingnew Date()
比 快(new Date()).getTime()
,但这Date.now()
比它们都快。
Browser support for Date.now()
isn't even that bad (IE9+):
浏览器支持Date.now()
甚至没有那么糟糕(IE9+):
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now
回答by Ben Glasser
when you create a new Date() object it is automagically initialized to the current time.
当您创建一个新的 Date() 对象时,它会自动初始化为当前时间。
From W3Schools:
来自 W3Schools:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
The getTime() function simply returns that time.
getTime() 函数只是返回那个时间。
From W3Schools:
来自 W3Schools:
Date.getTime() // method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.
回答by scott.korin
Date arithmetic converts dates to Epoch time (milliseconds since Jan 1 1970), which is why functionally the two code snippets are the same.
日期算术将日期转换为纪元时间(自 1970 年 1 月 1 日以来的毫秒数),这就是为什么两个代码片段在功能上是相同的。
As for which is faster, Jamund Ferguson's answer is correct.
至于哪个更快,贾蒙德弗格森的答案是正确的。