How to Set Default Time Zone in Node.js

Updated: December 2, 2023 By: Khue Post a comment

This short article walks you through 2 different ways to set the default time zone in Node.js. The first approach is to modify the TZ environment variable and the second one is to make use of a third-party package named set-tz (this library is really small and works well with TypeScript). No more meaningless talking, let’s get to the point.

Note: You can see the full list of tz database time zones on Wikipedia.

Using the TZ environment variable

You can set the TZ variable at runtime like this:

process.env.TZ = 'Etc/Universal'; // UTC +00:00
console.log(new Date().toString())

Output:

Sat Oct 28 2023 05:19:30 GMT+0000 (Coordinated Universal Time)

You should set the timezone on the first lines of your entry file and shouldn’t change it anywhere else later to avoid an unexpected outcome.

You can also set the TZ variable through your package.json file:

"scripts": {
    "start": "node TZ=Etc/Universal ./build/index.js",
    "dev": "TZ=Etc/Universal nodemon ./src/index.ts",
},

Or add it when bootstrapping your app:

node TZ=Etc/Universal ./build/index.js

Using a 3rd package

There are some good packages that can help you with the timezone stuff in Node.js. If you are writing code with only JavaScript, you can use timezone.js or node-time. If you prefer TypeScript, you can use set-tz.

Install set-tz:

npm i set-tz @types/set-tz

Then implement it like this:

import setTZ from 'set-tz';
setTZ('America/New_York')

console.log(new Date().toString())

And it should succeed with the following result:

Sat Oct 28 2023 01:25:36 GMT-0400 (Eastern Daylight Time)

Note that you may need to add "esModuleInterop": true to your tsconfig.json file to enable interoperability between CommonJS and ES Modules via the creation of namespace objects for all imports:

{
    "compilerOptions": {
        "esModuleInterop": true
    }
}

That’s it. Happy coding and surprise the world with your awesome Node.js applications!