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

Lucas Jellema 1

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:


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:


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:



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

  1. Hi,

    not sure if that solves your problem, but enforcing Node to be in a specific time zone might resolve it as well. There is the environment variable `TZ` you can overwrite before executing the Node process to change the timezone for it. So, for example `TZ=Etc/GMT node index.js` will force `new Date()` to work in the timezone Etc/GMT.

    Since I discovered this, I force all programs on all environments to work in UTC+0. It makes things so much simpler.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Next Post

Scheduling Oracle Cloud Function execution

Functions on Oracle Cloud are an important element in any cloud native application architectures. Functions are typically small, well contained and fairly independent pieces of logic to carry out specific tasks. These tasks can be executed upon reception and handling of HTTP requests – a very common use case – […]
%d bloggers like this: