How to get date with different timezone on bash scripts
Problem Statement
How to get date with different timezone on bash script
Problem Statement
I have a build script to build application, and I schedule to run it repeatedly, when there are new commits, I will send a message through the Telegram, and I will get the current date with date
command, there was a problem that the date is depending on the timezone of the server located. For example, I have a server on US, and I am in China, the time is not correct.
Solutions
There are several solutions to solve the problem.
Solution 1 — Change timezone on server
Change the server’s timezone to the destination we want, for example, change the timezone to China even the server is located on US, then the date
command will return the date that I want.
Solution 2 — Add timezone to UTC time
For example, I want to get the date in china which is in +8 timezone, how can I do it? I find we can use the following command, the -u
parameter will return the UTC time, and add 8 hours will return the time at +8 timezone.date -u -v+8H
Sample output$ date -u
Thu Jun 2 03:54:56 UTC 2022$ date -u -v+8H
Thu Jun 2 11:55:00 UTC 2022
Solution 3 — Specify timezone when use date command
The date
command can specify the timezone, so the following command is more readable.TZ='Asia/Shanghai' date
Sample outputdate
Wed Jun 1 21:08:12 PDT 2022TZ='Asia/Shanghai' date
Thu Jun 2 12:08:15 CST 2022
Conclusion
For me, I choose the third solution, because I don’t want change the server to the timezone that does not match the location it is. And the second one is still the UTC time, but added some hours on it. The third one is my prefer, it return the same date with the correct timezone.
🤝 Thanks for your reading!