How to get date with different timezone on bash scripts

Problem Statement

How to get date with different timezone on bash scripts

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!

Read more

AI读经 - 马太福音 第7章

AI读经 - 马太福音 第7章

这段经文出自《马太福音》第7章,是耶稣“登山宝训”的总结部分,主题集中在信徒的内在生命与外在行为。主要内容包括不论断他人(1-5节)、寻求神的帮助(7-12节)、选择生命的道路(13-14节)、提防假先知(15-20节)、真信徒的生命表征(21-23节)、以及听道与行道的重要性(24-27节)。这些教导旨在呼召信徒过敬虔和真实的生活,表现出神国的公义与恩典。

By Stephen Li