Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date() vs Date().getTime()

Tags:

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?

like image 446
Antony Avatar asked Mar 14 '13 04:03

Antony


People also ask

What does Date getTime () do?

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.

Is new Date () getTime () UTC?

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.

What is the difference between new Date () and Date ()?

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.

What does getTime return Date?

JavaScript Date getTime() getTime() returns the number of milliseconds since January 1, 1970 00:00:00.


1 Answers

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

like image 88
Jamund Ferguson Avatar answered Oct 07 '22 19:10

Jamund Ferguson