skip to Main Content

I want to set time zone of my Nodejs server running on ubuntu 20 to Asia/Tehran so:

First I changed ubuntu time zone using these command:

timedatectl set-timezone Asia/Tehran
and timedatectl shows that I set it corretly:

my@my-server:~$ timedatectl
Local time: Thu 2023-08-31 11:48:33 +0330
Universal time: Thu 2023-08-31 08:18:33 UTC
RTC time: Thu 2023-08-31 08:18:34
Time zone: Asia/Tehran (+0330, +0330)
System clock synchronized: yes
NTP service: active
RTC in local TZ: no

Then I set this line in my Nodejs server.js:

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

But time zone doesn’t changed at all!

Server side new Date() returns 2023-08-31T08:30:32.447Z although in Tehran it is Thu Aug 31 2023 12:00:32 GMT+0330 (Iran Standard Time)

What I’m doing wrong?

2

Answers


  1. You would need to probably set the environment variable before spinning up the server instance, so try running:

    env TZ='Asia/Tehran' node server.js
    

    This would set the timezone property correctly to Asia/Tehran. Now, running new Date() would return the ISO timestamp always, so to get the localized date/time format, you can use

    new Date().toLocaleString()
    

    which should return 8/31/2023, 2:15:30 PM (depending on your set TZ).

    To manipulate the formatting a bit more, I would prefer to use a date library like date-fns or day.js which provides advanced formatting abilities, including the ability to translate your result into a specific language (like Persian, for Tehran).

    Login or Signup to reply.
  2. Here’s what you can do to make sure your Node.js server also uses the correct time zone:

    1. Restart the Node.js Application: After changing the system time zone.

    2. Use process.env.TZ: Node.js allows you to set the TZ environment variable to specify the desired time zone for your application. Make sure you set this environment variable when you start your Node.js server. You can do this in your command line or in your Node.js script.

      Command Line:

      TZ=Asia/Tehran node your_server.js
      

      Node.js Startup Script:

      process.env.TZ = 'Asia/Tehran';
      // Rest of your server code
      
    3. Check Time Zone in Node.js: You can also print out the current time zone within your Node.js application to ensure that it’s correctly set

      console.log('Current Time Zone:', process.env.TZ);
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search