How to Set Default Time Zone in NodeJS
Time Zone in nodejs

Hi Guys, In this NodeJS article will work on timeZone, Basically will learn how to set default time zone in nodejs project.

This NodeJs Tutorial, we will learn the 2 ways by which we can set default timezone in nodejs applications.

2 ways to set default timezone in nodejs javascript

  1. Modifying TZ Environment variable.
  2. Using 3rd party package set-tz.

1. Defining default time zone using TZ Environment

To set time zone at runtime do this:

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


or 

process.env.TZ = 'Asia/Kolkata'; // UTC +05:30  Indian Standard TimeZone.
console.log(new Date().toString())

Output

Fri Feb 04 2022 06:10:01 GMT+0000 (Coordinated Universal Time)

Setting Time Zone default in package.json file

The TZ variable can also be set through package.json file:

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

2. using 3rd party packages i.e set-tz

In NodeJS There are various package library using which we can set default time zone, we will make use of set-tz.

Install set-tz in your node project

npm i set-tz @types/set-tz

How to use set-tz package

First we need to import set-tz from set-tz package where you want to apply default timezone, then by using setTZ() method you can pass which time zone you want to set (in my case I have set Asia/Kolkata)

import setTZ from 'set-tz';
setTZ('Asia/Kolkata')

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

Output

Fri Feb 04 2022 01:22:59 GMT+0530 

Conclusion

In this NodeJS article, We shown 2 technique through which we can easily set Time Zone for our NodeJS Project.