Search code examples
javascriptdateoverridingv8

How does console.log convert javascript date object into human readable format


Output of console.log({a:new Date()}) is { a: 2019-05-19T11:30:57.514Z }

Value of JSON.stringify({a:new Date()}) is {"a":"2019-05-19T11:33:12.591Z"}

After overriding this: Date.prototype.toJSON = function(){ return this.toLocaleString(); }

Value of JSON.stringify({a:new Date()}) is {"a":"5/19/2019, 5:09:31 PM"}

But output of console.log({a:new Date()}) is still { a: 2019-05-19T11:41:31.256Z }

Tried overriding other Date.prototype methods like toISOString(), toSource, toString, toUTCString, valueOf and many others. But none helped.

Couldn't understand the native source code of v8 js engine.

Any way to override the behavior to get the desired result?


Solution

  • It depends on the console implementation, which isn't in V8 but rather in the host (Chrome, Chromium, Node.js, ...).

    Node.js used to look for a member called inspect (back in v4 at least) and use that if it was present, but that turned out to be a compatibility problem and it doesn't do that anymore.

    I don't think there's any way to override the console's rendering of built-in objects anymore, particularly not across host environments.