How to get the local timezone from the system using nodejs

Is there a way to obtain the local timezone from the system (eg:- ubuntu) using nodejs?

I used moment.js to extract the date and time values. But couldn't find a way to extract the timezone as well.


Solution 1:

The existing answers will tell you the current timezone offset, but you will have issues if you are comparing historic/future points in time as this will not cater for daylight saving changes.

In many timezones, the offset varies throughout the year and these changes occur at different dates or not at all depending on the latitude. If you only have UTC time and an offset, you can never be sure what the offset will be in that location at various other times during the year.

For example, a UTC+2:00 offset could refer to Barcelona in the summer or Ivory Coast all year round. The 2hr offset will always display the correct time in Ivory Coast but will be 1hr out for half the year in Barcelona.

Check out this article covering the above.

How do we cater for all these time zone issues? Well, it's pretty simple:

  1. Save all times in UTC
  2. Store the time zone string for where this event occurred

In modern browsers or node.js, you can get the local IANA time zone string like this:

Intl.DateTimeFormat().resolvedOptions().timeZone // eg. 'America/Chicago'

You can then use this timezone string in a library like Luxon to help offset your captured UTC times.

DateTime.fromISO("2017-05-15T09:10:23", { zone: "Europe/Paris" });

Solution 2:

It is very simple.

var x = new Date();
var offset= -x.getTimezoneOffset();
console.log((offset>=0?"+":"-")+parseInt(offset/60)+":"+offset%60)

And there is nothing else or you can see if momentJS can help you or not.