将 UTC 时间转换为 GMT bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32041793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert UTC time to GMT bash script
提问by Oum Alaa
I am trying to convert a UTC time to GMT time in my small script, but it doesn't work:
我试图在我的小脚本中将 UTC 时间转换为 GMT 时间,但它不起作用:
TimestampUTC=$(date +"%s")
echo $TimestampUTC
dates=$(date -d @$TimestampUTC)
echo $dates
## 2 hours difference between UTC and GMT
Hours2=120
TimestampGMT=$((TimestampUTC - Hours2))
echo $TimestampGMT
diff=$((TimestampUTC - TimestampGMT))
echo $diff
dateGMT=$(date -d @$TimestampGMT)
echo $dateGMT
The displayed result for $dateGMT
is the same as $dates
.
的显示结果$dateGMT
与 相同$dates
。
Thanks in advance.
提前致谢。
回答by Gunstick
error in script.
脚本错误。
Unix timestaps are given in seconds.
Unix 时间戳以秒为单位。
Hours2=120 means 120 seconds.
小时 2=120 表示 120 秒。
So your 2 timestaps are diverging by 2 minutes, not 2 hours.
因此,您的 2 个时间戳相差 2 分钟,而不是 2 小时。
This code is correct:
这段代码是正确的:
Hours2=7200
Also you claim having 2 hours between GMT and UTC, I'm sure you mean CET (central european time)
您还声称 GMT 和 UTC 之间有 2 小时,我确定您指的是 CET(中欧时间)
Note: there is nothing like a CET timestamp. It's just the normal unix timestamp displayed with a timezone offset. So independently of world location, the unix timestamp is always, worldwide, the same at the same instant.
注意:没有什么比 CET 时间戳更像的了。这只是显示时区偏移的普通 unix 时间戳。因此,独立于世界位置,unix 时间戳在同一时刻在全球范围内始终相同。
You can replace all your code by just this
你可以用这个替换你所有的代码
# get the timestamp 2 hours in the future from now
date2h=$(date -d "2 hours" +%s)
Which gives you the unix timestamp from the future. It is NOT the current timestamp in CET. The current CET timestamp is always the same as UTC.
这为您提供了未来的 Unix 时间戳。它不是 CET 中的当前时间戳。当前的 CET 时间戳始终与 UTC 相同。
How to get the time from UTC and CET? Set the environment variable TZ before the command.
如何从UTC和CET获取时间?在命令之前设置环境变量 TZ。
$ TZ=UTC date
Mon Aug 17 11:44:05 UTC 2015
$ TZ=CET date
Mon Aug 17 13:44:05 CEST 2015
$ TZ=GMT date
Mon Aug 17 11:44:05 GMT 2015
but the timestap is always the same
但时间戳总是一样的
$ TZ=UTC date +%s
1439812072
$ TZ=CET date +%s
1439812072
$ TZ=GMT date +%s
1439812072
回答by SkySpiral7
GMT and UTC do not differ by 2 hours. In fact they don't differ at all. So displaying the dates of GMT and UTC will always show exactly the same number.
GMT 和 UTC 相差 2 小时。事实上,它们根本没有区别。因此,显示 GMT 和 UTC 的日期将始终显示完全相同的数字。
Also I don't know bash but I find it hard to believe that 2 hours is represented by 120 minutes. Normally when doing math with dates milliseconds are used.
我也不知道 bash,但我发现很难相信 2 小时是由 120 分钟表示的。通常在使用日期进行数学运算时会使用毫秒。