One of the newer functions that was added as of the 5th edition of ECMA-262 is Date.now(). This function returns the number of milliseconds that have passed since January 1, 1970 at midnight GMT time (UTC). If you desire to write code that uses this newer function, in order to make sure that it works in any browser, you can use the following code which was derived from this MDN Doc:


Date.now = Date.now || function() {
  return +new Date;
};

Even though this function can easily be used, believe it or not, you can make the calls to get this data even more convenient. Instead of using the above definition, you can use the following one:


Date.valueOf = Date.now = Date.now || function() {
  return +new Date;
};

Now, by using these two definitions, you can simply use +Date to get the amount of milliseconds since January 1, 1970. Here is an example of using this simple trick to display a meaningful message:


alert("Milliseconds since 1970 00:00:00 UTC:  " + Date);

The reason this works is because when you prefix an object with the plus sign, that object’s valueOf() function is automatically called. That is the same reason why prefixing an instance of the Date object with a plus sign results in the amount of milliseconds between that date and January 1, 1970. The beauty of this definition is the fact that it not only provides this shortcut, but it also makes sure that the Date.now() function is available to use. Here is the equivalent of the previous example:


alert("Milliseconds since 1970 00:00:00 UTC:  " + Date.now());

As of right now, I don’t know of any downsides to redefining Date.valueOf(), but if you find any, please let me know.

Categories: BlogJavaScriptJScript

2 Comments

swaydeng · September 28, 2012 at 7:29 AM

Rewriting “valueOf” is inappropriate, because the method’s function is returning primitive value of a Date, instead of just returning a simple “now” thing, like you can’t rewrite “getTime”.

    Chris West · September 28, 2012 at 10:12 AM

    You present a great point. For that reason, I would say that the developer should only rewrite the valueOf() function if they don’t care to have access to the primitive value of a Date.

Leave a Reply to swaydeng Cancel reply

Your email address will not be published. Required fields are marked *