我写了一个运行在 OpenWRT 上的 Golang 程序。
package main
import (
"fmt"
"time"
)
func main(){
fmt.Println(time.Now())
}
Run Code Online (Sandbox Code Playgroud)
当我在我的 Macbook 上运行这个程序时,我总是得到正确的本地时间。
但是,在 OpenWRT 上运行这个程序时,我总是得到 UTC 时间。
我已经设置了 OpenWRT 的时区和时间。当我执行时uci show system,我可以看到正确的时区。当我执行date正确的本地时间可以正确显示。
所以我的问题是,如何在 OpenWRT 上使用 Golang 的 time.Now() 获得正确的当地时间?
我的问题的根源在于我的 OpenWRT 缺少 zoneinfo 包。所以我先跑opkg update && opkg install zoneinfo-xxx。
这是 go/src/time/zoneinfo_unix.go 的一部分:
func initLocal() {
// consult $TZ to find the time zone to use.
// no $TZ means use the system default /etc/localtime.
// $TZ="" means use UTC.
// $TZ="foo" means use /usr/share/zoneinfo/foo.
...
}
Run Code Online (Sandbox Code Playgroud)
根据这个文件,如果没有“TZ”变量,Golang在调用time.Now()时会使用/etc/localtime指向的时区。
然后我在/etc/config/system(选项 zonename 'xxxxxx')设置时区并运行/etc/init.d/system restart. 最后,我可以得到正确的 time.Now()。