POSIX 数字时区
POSIX numeric time zone
我可以这样得到数字时区:
$ date +%z
-0600
不过我最近发现POSIX日期只支持打印
timezone name:
$ date +%Z
CST
我可以使用 shell 或其他工具获得数字版本,同时坚持使用
POSIX?
TZ variable是由POSIX定义的,所以我们可以循环不同的时间
区域,直到我们找到匹配的区域:
q=$(date +%H)
x=-12
while [ "$x" -le 11 ]
do
y=$(TZ=UTC"$x" date +%H)
if [ "$y" = "$q" ]
then
printf '%+03d00\n' "$((-x))"
break
fi
x=$((x + 1))
done
仅当您的时区和 UTC 之间的日期没有变化时才有效。它还会省略分钟,例如,如果您在印度,这将不起作用。
为此,您需要更多日期信息:一年中的第几天和整点后的分钟数。
#!/bin/sh
T='+%j*1440+%H*60+%M' # minutes in year: DAY/Y * 1440 min/d + H * 60 h/min + MIN
Z=$(( ( $(date "$T") - ( $(date -u "$T") ) ) * 100 / 60 )) # TZ offset as hr*100
H=${Z%??} # hours ($Z is hundredths of hours, so we remove the last two digits)
if [ $H -lt -13 ]; then H=$((H+8712)) # UTC is a year ahead
elif [ $H -gt 13 ]; then H=$((H%8736-24)) # UTC is a year behind
fi
if [ $H -lt -13 ]; then H=$((H+24)) # UTC is a day ahead of a leap year
elif [ $H -gt 13 ]; then H=$((H-24)) # UTC is a day behind a leap year
fi
M=${Z#$H} # hundredths of hours (to become minutes on the next line)
if [ $M != 00 ]; then M=$(( $M * 60 / 100 )); fi # Minutes relative to 60/hr
printf '%+03d%02d' $H $M # TZ offset in HHMM
这让您可以通过更改 $TZ
来更改时区,因此 TZ=Asia/Calcutta myscript.sh
应该会产生 +0530
的 TZ 偏移量。 (这部分可能不适用于较旧的 POSIX 系统。)
我可以这样得到数字时区:
$ date +%z
-0600
不过我最近发现POSIX日期只支持打印 timezone name:
$ date +%Z
CST
我可以使用 shell 或其他工具获得数字版本,同时坚持使用 POSIX?
TZ variable是由POSIX定义的,所以我们可以循环不同的时间 区域,直到我们找到匹配的区域:
q=$(date +%H)
x=-12
while [ "$x" -le 11 ]
do
y=$(TZ=UTC"$x" date +%H)
if [ "$y" = "$q" ]
then
printf '%+03d00\n' "$((-x))"
break
fi
x=$((x + 1))
done
为此,您需要更多日期信息:一年中的第几天和整点后的分钟数。
#!/bin/sh
T='+%j*1440+%H*60+%M' # minutes in year: DAY/Y * 1440 min/d + H * 60 h/min + MIN
Z=$(( ( $(date "$T") - ( $(date -u "$T") ) ) * 100 / 60 )) # TZ offset as hr*100
H=${Z%??} # hours ($Z is hundredths of hours, so we remove the last two digits)
if [ $H -lt -13 ]; then H=$((H+8712)) # UTC is a year ahead
elif [ $H -gt 13 ]; then H=$((H%8736-24)) # UTC is a year behind
fi
if [ $H -lt -13 ]; then H=$((H+24)) # UTC is a day ahead of a leap year
elif [ $H -gt 13 ]; then H=$((H-24)) # UTC is a day behind a leap year
fi
M=${Z#$H} # hundredths of hours (to become minutes on the next line)
if [ $M != 00 ]; then M=$(( $M * 60 / 100 )); fi # Minutes relative to 60/hr
printf '%+03d%02d' $H $M # TZ offset in HHMM
这让您可以通过更改 $TZ
来更改时区,因此 TZ=Asia/Calcutta myscript.sh
应该会产生 +0530
的 TZ 偏移量。 (这部分可能不适用于较旧的 POSIX 系统。)