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

20

270

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

Heine answered 10/11, 2011 at 17:4 Comment(4)
Pretty sure you can't really do that. Change the systems timezone settings.Reyna
thejh is right, you cannot change the timezone. Use a JS time library (like moment.js) and add / subtract hours instead.Compiler
The easiest and the correct way to do this is to simply change your system's time zone.Pyne
These are useful comments but most of the time you are not the system manager ;)Protecting
O
248

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.

Oberhausen answered 24/3, 2012 at 5:55 Comment(9)
Doesn't work all the time, there's a bug open about this: github.com/joyent/node/issues/3286.Publicity
That's interesting. The bug discussion suggests it's some issue with threading. But the example was changing process.env.TZ multiple times. It looks like setting it once at the beginning and leaving it alone works. Thanks lorancou for the reference to node-time, though, for more flexible and robust handling.Oberhausen
Sadly, it does not work in windows. Works well in mac os-x and unixBalakirev
Nice answer. Unfortunately, every single time I see something like process.env.TZ = 'Europe/Amsterdam' I think "nice, now where can I find a list of all valid values that I can set?" and I don't find it, every single time.Andrey
@RafaelEyng the IANA (International Assigned Numbers Association) is often used for provision of up to date timezone configurations. You can find the latest timezone settings here: ftp.iana.org/tz/tzdata-latest.tar.gz For an overview of the possible timezone strings check the zone.tab file in that archive.Rank
By the way this is not a node feature, it's a linux c bindings feature man7.org/linux/man-pages/man7/environ.7.htmlBurgett
@RafaelEyng: as JohannesB mentioned iana.org/time-zones is the official source, but their data format is hard to work with. I find it much easier to work from en.wikipedia.org/wiki/List_of_tz_database_time_zones, which is built from the IANA dataset (currently the 2017c version).Kennel
The one for UTC is Etc/UTC. This has the huge side bonus of printing ISO8601 times by default.Cheeseparing
momentjs.com/timezoneLeslie
D
105

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.

Diabolo answered 16/2, 2016 at 12:1 Comment(3)
Can you do the same for cultures?Develop
This made it way simpler to force a timezone, than trying to do so in code.Dactylic
For Windows (via powershell), simply type this command before: $env:TZ = 'Europe/Amsterdam' And by the way, if you don't want a timezone, you have to put: $env:TZ = 'UTC'Bodwell
N
63

Here is a 100% working example for getting custom timezone Date Time in NodeJs without using any external modules:

const nDate = new Date().toLocaleString('en-US', {
  timeZone: 'Asia/Calcutta'
});

console.log(nDate);
Notecase answered 11/1, 2018 at 12:15 Comment(2)
I'm puzzled - this is very upvoted but it has a critical problem IMO. Node versions < 13 only have locale data for 'en-us', which means it throws (in some cases) or gives the wrong date format for every other country. And in many cases the date will look correct but day & month are swapped ! And Node 13 was only just released a few weeks ago so this problem applies to pretty much everyone.Zulema
I see that the answer by @Marshall below suggests a way to solve this in some situations (won't work in Lambda and other FaaS).Zulema
P
40

Unfortunately, setting process.env.TZ doesn't work really well - basically it's indeterminate when the change will be effective).

So setting the system's timezone before starting node is your only proper option.

However, if you can't do that, it should be possible to use node-time as a workaround: get your times in local or UTC time, and convert them to the desired timezone. See How to use timezone offset in Nodejs? for details.

Publicity answered 30/5, 2012 at 23:53 Comment(3)
npm module time worked great for me. i set to utc, then set all times using utc, so code is portable between different machines with different timezones.Runkel
There are no issues with this any longer, are there?Margertmargery
@Margertmargery It seems to have been fixed in Node 13 (https://mcmap.net/q/108554/-how-can-i-set-the-default-timezone-in-node-js), however it might still be safest to set TZ before starting Node. For example, Jest doesn't properly handle TZ yet: Setting process.env.TZ does not affect DatesDemanding
T
32

just set environment variable in your main file like index.js or app.js or main.js or whatever your file name is:

process.env.TZ = "Asia/Tehran";

this will set the timezone which will be used in your entire node application

Tade answered 4/7, 2020 at 6:46 Comment(0)
K
21

As of Node 13, you can now repeatedly set process.env.TZ and it will be reflected in the timezone of new Date objects. I don't know if I'd use this in production code but it would definitely be useful in unit tests.

> process.env.TZ = 'Europe/London';
'Europe/London'
> (new Date().toString())
'Fri Mar 20 2020 09:39:59 GMT+0000 (Greenwich Mean Time)'

> process.env.TZ = 'Europe/Amsterdam';
'Europe/Amsterdam'
> (new Date().toString())
'Fri Mar 20 2020 10:40:07 GMT+0100 (Central European Standard Time)'
Kinsfolk answered 20/3, 2020 at 9:59 Comment(5)
This works great on Linux/Mac, but doesn’t work on Windows.Affranchise
No it works for Windows too, use set TZ='UTC' node index.jsNorth
@North no, that syntax sets the env var for the whole process - not while running as in the OP's example.Arc
Setting TZ to undefined makes GMT the timezone. To revert back to system default, you have to do delete process.env.TZ;.Siglos
new Date() is showing different result than new Date().toString() :(Pyrolysis
V
19

The solution env TZ='Europe/Amsterdam' node server.js from @uhef works in cases where your app doesn't work with forked process, but when you are working with forked process, specially when you launch your app with a building tool like gulp , the command gulp will take the env values, but the process created by gulp not (your app).

To solve this, you have to do:

$ export TZ="Europe/Amsterdam"; gulp myTask

This will set the TZ environment variable for all the process started in the console you are working on, included all the subsequents process executed after the gulp command in the same console without the need to execute them with the prefix export TZ="Europe/Amsterdam"; again.

Vazquez answered 14/7, 2016 at 12:26 Comment(2)
since amsterdam has DST, is this still the desirable tz to achieve "midnight UTC" at GMT +1?Brozak
@Brozak I use Etc/UTC There are also specific offsets available in Etc, but the offset is reverse of what one would expect. Etc/GMT-1 is UTC + 1 hour. See https://en.wikipedia.org/wiki/List_of_tz_database_time_zonesMargaretmargareta
M
13

Set server timezone and use NTP sync. Here is one better solution to change server time.

To list timezones

timedatectl list-timezones

To set timezone

sudo timedatectl set-timezone America/New_York

Verify time zone

timedatectl

I prefer using UTC timezone for my servers and databases. Any conversions must be handled on client. We can make used of moment.js on client side.

It will be easy to maintain many instances as well,

Mair answered 10/11, 2011 at 17:4 Comment(1)
While moment.js was a great library back in the day, there are far smaller alternatives currently (e.g. date-fns). Moment is huge; please do not recommend it for client applications.Dactylic
E
8

I know this thread is very old, but i think this would help anyone that landed here from google like me.

In GAE Flex (NodeJs), you could set the enviroment variable TZ (the one that manages all date timezones in the app) in the app.yaml file, i leave you here an example:

app.yaml

# [START env]
env_variables:
  # Timezone
  TZ: America/Argentina/Buenos_Aires
Erlineerlinna answered 29/8, 2017 at 14:21 Comment(0)
M
7

Here's an answer for those deploying a Node.js application to Amazon AWS Elastic Beanstalk. I haven't seen this documented anywhere else:

Under Configuration -> Software -> Environment Properties, simply set the key value pair TZ and your time zone e.g. America/Los Angeles, and Apply the change.

You can verify the effect by outputting new Date().toString() in your Node app and paying attention to the time zone suffix.

Melodics answered 1/2, 2018 at 3:51 Comment(0)
N
6

You could enforce the Node.js process timezone by setting the environment variable TZ to UTC

So all time will be measured in UTC+00:00

Full list: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Example package.json:

{
  "scripts": {
    "start": "TZ='UTC' node index.js"
  }
}
North answered 10/5, 2020 at 22:27 Comment(1)
This doesn’t work on Windows. You can’t set the TZ env var this way. And if you do set TZ, it won’t be recognized as Node’s default timezone.Affranchise
M
5

You just need to set it when you're starting your app.

{
  "scripts": {
    "start:timezone": "TZ='utc' node index.js",
    "start": "TC=$tz node index.js"
  }
}

In your CI or wherever you want to start the app, you can either statically run it like npm run start:timezone OR dynamically pass your timezone to the process like npm run start utc

Another approach could be to set it in your app's entrypoint like so:

process.env.TZ = "UTC";
Middy answered 17/3, 2023 at 16:45 Comment(0)
T
4

Update for node.js v13

As @Tom pointed out, full icu support is built in v13 now. So the setup steps can be omitted. You can still customize how you want to build or use icu in runtime: https://nodejs.org/api/intl.html

For node.js on Windows, you can do the following:

  1. Install full-icu if it has been installed, which applies date locales properly

    npm i full-icu or globally: npm i -g full-icu

  2. Use toLocaleString() in your code, e.g.:

    new Date().toLocaleString('en-AU', { timeZone: 'Australia/Melbourne' })

    This will produce something like: 25/02/2019, 3:19:22 pm. If you prefer 24 hours, 'en-GB' will produce: 25/02/2019, 15:19:22

For node.js as Azure web app, in addition to application settings of WEBSITE_TIME_ZONE, you also need to set NODE_ICU_DATA to e.g. <your project>\node_modules\full-icu, of course after you've done the npm i full-icu. Installing the package globally on Azure is not suggested as that directory is temporary and can be wiped out.

Ref: 1. NodeJS not applying date locales properly

  1. You can also build node.js with intl options, more information here
Taler answered 25/2, 2019 at 5:43 Comment(1)
full-icu is included in the standard/official builds of Node as of v13 so the above steps will no longer be necessary.Zulema
T
2

You can take moment timezone. It lets you set your location and also takes care of daylight saving time.

Typical answered 31/10, 2015 at 20:0 Comment(1)
moment is pretty heavyweight for a task like this and I wouldn't recommend it unless the behavior you want is not possible through Date or other builtin modules.Crowns
P
2

Sometimes you may be running code on a virtual server elsewhere - That can get muddy when running NODEJS or other flavors.

Here is a fix that will allow you to use any timezone easily.

Check here for list of timezones

Just put your time zone phrase within the brackets of your FORMAT line.

In this case - I am converting EPOCH to Eastern.

//RE: https://www.npmjs.com/package/date-and-time
const date = require('date-and-time');

let unixEpochTime = (seconds * 1000);
const dd=new Date(unixEpochTime);
let myFormattedDateTime = date.format(dd, 'YYYY/MM/DD HH:mm:ss A [America/New_York]Z');
let myFormattedDateTime24 = date.format(dd, 'YYYY/MM/DD HH:mm:ss [America/New_York]Z');
Phenocryst answered 3/8, 2019 at 8:59 Comment(0)
P
1

i work with this npm package unix-system-timezone

Precept answered 21/8, 2019 at 14:15 Comment(0)
V
1

You can config global timezone with the library tzdata:

npm install tzdata -y

After set your environment with the variable for example: TZ=America/Bogota

And testing in your project:

new Date()

I hope helpyou

Valrievalry answered 18/2, 2020 at 13:58 Comment(0)
H
1

Just process.env.TZ = "Asia/Dhaka"; //SET Default Timezone on app.js after the import of your modules and it will gonna work for your whole project.

Hydrogenize answered 31/5, 2023 at 5:32 Comment(0)
L
0

const nDate = new Date().toLocaleString('en-US', {
  timeZone: 'Asia/Seoul'
});

console.log(nDate);
Laryngology answered 19/9, 2022 at 5:32 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Grande
S
-3

This works; https://mcmap.net/q/110710/-momentjs-todate-timezone-gets-reset

var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);
Sami answered 17/12, 2021 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.