Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  11] [ 6]  / answers: 1 / hits: 100427  / 11 Years ago, thu, march 14, 2013, 12:00:00

What is the difference between using new Date() and new Date().getTime() when subtracting two timestamps? (test script on 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?


More From » date

 Answers
14

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



The above link shows using new Date() is faster than (new Date()).getTime(), but that Date.now() is faster than them all.



Browser support for Date.now() isn't even that bad (IE9+):



https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now


[#79609] Tuesday, March 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
korbindarrionh

Total Points: 598
Total Questions: 113
Total Answers: 104

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;