2 Ways to Set Default Time Zone in Node.js
( 64 Articles)

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:
Fri Feb 04 2022 06:10:01 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:
Fri Feb 04 2022 01:22:59 GMT-0500 (Eastern Standard Time)
Conclusion
You’ve learned more than one technique to change the default timezone for a Node.js application. If you’d like to explore more new and interesting things in the modern Node.js world, take a look at the following articles:
- 4 Ways to Read JSON Files in Node.js
- Node.js: Use Async Imports (Dynamic Imports) with ES Modules
- Node + Mongoose + TypeScript: Defining Schemas and Models
- Top 4 best Node.js Open Source Headless CMS
- Best Open-Source HTTP Request Libraries for Node.js
You can also check out our Node.js category page for the latest tutorials and examples.
I did the first method and I couldn’t, it always returns the time zone of my country, even if I set London
I’ll recheck the example
Hey Edurdo, make sure you correctly type the time zone. You can copy from here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
k