Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the default timezone in node.js?

How do I set the default timezone in node.js?

like image 866
Olu Avatar asked Oct 11 '22 17:10

Olu


People also ask

How do I set the default timezone for a moment?

To reset the default time zone to local, use moment. tz. setDefault with no arguments.

How do I get current timezone in node JS?

you can also use moment(). format('Z') to get the same result. This gives you the current offset in your current timezone but this may vary for part of the year due to DST changes. If in doubt, always use/store UTC date/times plus the timezone identifier and then convert to local as late as possible.

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() .

What is the default timezone of new date in JavaScript?

Sometimes, we may want to initialize a JavaScript date to a particular time zone. The default time zone is UTC.


2 Answers

According to this google group thread, you can set the TZ environment variable before calling any date functions. Just tested it and it works.

> process.env.TZ = 'Europe/Amsterdam' 
'Europe/Amsterdam'
> d = new Date()
Sat, 24 Mar 2012 05:50:39 GMT
> d.toLocaleTimeString()
'06:50:39'
> ""+d
'Sat Mar 24 2012 06:50:39 GMT+0100 (CET)'

You can't change the timezone later though, since by then Node has already read the environment variable.

like image 218
webjprgm Avatar answered Oct 14 '22 05:10

webjprgm


Another approach which seemed to work for me at least in Linux environment is to run your Node.js application like this:

env TZ='Europe/Amsterdam' node server.js

This should at least ensure that the timezone is correctly set already from the beginning.

like image 95
uhef Avatar answered Oct 14 '22 06:10

uhef