/ Published in: JavaScript
Expand |
Embed | Plain Text
var foo = new Date(); var bar = new Date(); var baz = new Date(); baz.setTime(bar.getTime() - foo.getTime()); alert(baz.getMilliseconds() + " ms elapsed between the definition of foo and bar.");
Comments
Subscribe to comments
You need to login to post a comment.

This is incorrect!
getMilliseconds() returns the number of milliseconds into the current second of the timestamp contained by the Date(), like a modulo (%) for milliseconds. If used with an unset Date() object, it will return the number of milliseconds into the current second of the current clock time. So this code will only return a number from 0-999.
You can check this with this code:
var foo = new Date(); setTimeout( function() { var bar = new Date(); var baz = new Date(); baz.setTime(bar.getTime() - foo.getTime()); alert(baz.getMilliseconds() + " ms elapsed between the definition of foo and bar."); }, 2500);
The result will be close to 500, instead of 2500.
Here's a better way to do it:
var foo = new Date(); var bar = new Date(); var diff = bar - foo; alert(diff + " ms elapsed between the definition of foo and bar.");