22

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?

Antony
  • 14,900
  • 10
  • 46
  • 74

3 Answers3

63

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

Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
4

when you create a new Date() object it is automagically initialized to the current time.

From 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.

From W3Schools:

Date.getTime() // method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.

http://www.w3schools.com/jsref/jsref_obj_date.asp

Ben Glasser
  • 3,216
  • 3
  • 24
  • 41
  • I'm not sure whether my reading comprehension is off or whether you aren't explaining `getTime()` correctly. It sounds like you are saying the value of getTime() will change between the time when the `Date` object is created when when the function is called. That's not what you meant, was it? – scott.korin Mar 14 '13 at 04:37
4

Date arithmetic converts dates to Epoch time (milliseconds since Jan 1 1970), which is why functionally the two code snippets are the same.

As for which is faster, Jamund Ferguson's answer is correct.

scott.korin
  • 2,537
  • 2
  • 23
  • 36