Override Date.now() based on OS time when Node returns incorrect current date image 102

Override Date.now() based on OS time when Node returns incorrect current date

I was facing a weird issue. In my Node application – version 10.6.3 – running on Ubuntu – 18.04 – I got the wrong value for the current date and time. A call to new Date() and to Date.now() resulted in a wrong value, off by over two months:

image

The top two values are the formatted date and value for now:

console.log(new Date())
console.log( Date.now())

The other values are the date reported by the operating system. For some bizarre reason, the value constructed in the Node runtime engine is off by two months, 27 days and over 14 hours.

I do not know why this is. I have not been able to find a cause nor a fix.

To make my programs at least function correctly, I have added a detection of this spread between JavaScript Date and OS Date and an override of the now() function on the Date object to make things right – or at least functioning. I later realized that overriding now() is useful for running tests that have to mock a specific date and time or for running a prank on your colleagues.

A little example of what I did:

image

const { execSync } = require('child_process');

console.log(`Date according to Node: ${new Date()}`)
console.log(`result of Date.now():  ${Date.now()}`)

const da = execSync('date');
console.log(`OS date and time ${da}`)
const d = Date.parse(da)
console.log(`OS timestamp in ms ${d}`)

if (d - Date.now() > 10000) {
    Date.now = function () {
        const da = execSync('date');
        console.log(`in now - OS date ${da}`)
        console.log(`in now OS date as JS ${new Date(da).toISOString()}`)
        const d = Date.parse(da)
        return d;
    }
}
console.log("After fixing Date.now() through override:")
console.log(`Date according to Node: ${new Date()}`)
console.log(`result of Date.now():  ${Date.now()}`)

And here is the outcome of running that code:

image

 

One Response

  1. Peter Merkert December 30, 2019