Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does Node.js get it's timezone and how can I set it globally?

I am running Windows 10 Professional and my timezone and region settings are set to Brisbane/Australia (UTC+ 10:00). Furthermore, I am running Node.js on my system for an application I am building.

I ran the following in Node.js:

  var x = new Date();
  console.log(x);

It returned the following:

2017-09-07T23:42:33.719Z

Notice the Z at the end of the datetime string? This represents Zulu time. (UTC + 0)

I presume that this is set by default in Node.js when no timezone is specified. How can I specify the timezone globally in Node.js so as to ensure that all date objects a returned correctly?

like image 420
cleverpaul Avatar asked Sep 08 '17 00:09

cleverpaul


People also ask

Where does JavaScript get timezone from?

To get the current browser's time zone, you can use the getTimezoneOffset() method from the JavaScript Date object.

How do I get current UTC time in node js?

Use the toUTCString() method to get the current date and time in utc, e.g. new Date(). toUTCString() .


1 Answers

You can set the TZ env to a timezone string.

For example:

$ export TZ=Europe/Amsterdam
$ node

> Date()
'Fri Sep 08 2017 03:02:57 GMT+0200 (CEST)'


$ export TZ=America/Anchorage
$ node

> Date()
'Thu Sep 07 2017 17:04:46 GMT-0800 (AKDT)'

You can also set process.env.TZ at runtime:

> process.env.TZ = 'Antarctica/Mawson'

> Date()
'Thu Sep 07 2017 17:11:00 GMT-0800 (+05)'

Note, regardless of the timezone, new Date() returns UTC 2017-09-08T01:05:58.103Z when called like this.

like image 126
Mark Avatar answered Sep 30 '22 20:09

Mark