Working with Time and Date in Node js

Some basic concepts:

Arun Rajeevan
1 min readDec 3, 2020

a) How to represent time in an universal format?
Answer: As a number
Explanation:
Epoch time — The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970.
Ex: 1606982441

In Nodejs,

let dateNow = Date.now();
console.log(dateNow) //1606984719575

So dateNow is a number and is in Unix Epoch.

b) How to convert time in number to specific date and time according to timezone?

let date = new Date(dateNow)
let temp = date.toLocaleDateString(undefined, {timeZone:’Asia/Kolkata’});
console.log(temp) // 3/12/2020

Important note: The response of date.toLocaleDateString is dependent on the Operating system or Platform.

In Windows, the output will be 3/12/2020 i.e dd-mm-yyyy
In Linux, the output will be 12/3/2020 i.e mm-dd-yyyy.

Small piece of advice to all of you:

Please consider O.S while working with Time or Date.
Have proper logging in place if incase some weird issue happens(based on my experience).

What I experienced!!

My development setup was using Windows and my code was working fine.
After deployment, it was not working.
The deployment environment was Linux and the dates were different and my query were not returning results. Luckily I had logs after each date manipulation code and I could figure out the issue.

Another observation:
In Nodejs 12, it will give you month/date/year, but in Nodejs 14, it will give date/month/year.

Finally I admit the evil aspects of upgrading to the latest versions of any framework without proper test cases in place.

--

--