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?
Javascript date getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00. You can use this method to help assign a date and time to another Date object.
Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.
Date() returns an implementation dependent string representing the current date and time. new Date() returns a Date object that represents the current date and time. ;-) Yeah, I know.
JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With