Working with Time and Date in Node js

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.

Suffering from Knowledge Quest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store