I just ran across a usage of Date.now()
in a web application and noticed it throwing an error in IE8, our lowest common denominator of a browser. Here is a quick fix to make sure you get your number value back in all browser.
“The
now()
method returns the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now as aNumber
.”
Minimum Browser for Date.now()
Browser | Version |
---|---|
Chrome | 5 |
Firefox (Gecko) | 3 |
Internet Explorer | 9 |
Opera | 10.50 |
Safari | 4 |
Solid Tip: Date.now()
is much faster than old methods (but doesn’t work before IE9). Compare them with this performance test.
Proper Method for Older Browsers
JAVASCRIPTview code
new Date().getTime(); |
If You Want Date.now() as a Function
Mozilla suggests the following shim with an expression to solve your issues.
JAVASCRIPTview code
if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } |
If you end up adding the function yourself so that it is available, be sure to put the date into a variable so it doesn’t keep having to be instantiated. It will provide ~20% faster performance.