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
You would need to probably set the environment variable before spinning up the server instance, so try running:
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 usewhich 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).
Here’s what you can do to make sure your Node.js server also uses the correct time zone:
Restart the Node.js Application: After changing the system time zone.
Use
process.env.TZ
: Node.js allows you to set theTZ
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:
Node.js Startup Script:
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