【问题标题】:Why running Golang's time.Now() at OpenWRT always get UTC time?为什么在 OpenWRT 上运行 Golang 的 time.Now() 总是得到 UTC 时间?
【发布时间】:2019-01-04 08:26:08
【问题描述】:

我写了一个在 OpenWRT 上运行的 Golang 程序。

package main

import (
    "fmt"
    "time"
)

func main(){
    fmt.Println(time.Now())
}

当我在我的 Macbook 上运行这个程序时,我总是得到正确的当地时间。

但是,在 OpenWRT 上运行这个程序时,我总是得到 UTC 时间。

我已经设置了OpenWRT的时区和时间。当我执行uci show system 时,我可以看到正确的时区。当我执行date 时,正确的本地时间可以正确显示。

所以我的问题是,如何在 OpenWRT 上使用 Golang 的 time.Now() 获得正确的当地时间?

【问题讨论】:

  • 不确定这是否有帮助,但 here 是 go 在类似 unix 的系统上确定本地时区的方式。
  • 谢谢。这正是我所需要的。

标签: go openwrt


【解决方案1】:

我的问题的根源是我的 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.

    ...

}

根据这个文件,如果没有“TZ”变量,Golang在调用time.Now()时会使用/etc/localtime指向的时区。

然后我将时区设置为/etc/config/system(选项 zonename 'xxxxxx')并运行/etc/init.d/system restart。终于可以得到正确的time.Now()了。

【讨论】:

    【解决方案2】:

    OpenWRT 将时区存储在一个名为 /etc/TZ 的文件中。如果此文件丢失或为空,OpenWRT 假定本地时间等于 UTC 时间。 Source

    如何使用 Golang 的 time.Now() 获取正确的本地时间 OpenWRT?

    Specifying the Time Zone with TZ

    这是您必须添加或减去本地时间才能获得 UTC 时间的值。如果本地时区在本初子午线以西,则此偏移量将为正,如果在东则为负。

    【讨论】:

    • 感谢您的回复!我通过安装 zoneinfo 包并在 /etc/config/system 设置选项 zonename 解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2016-11-22
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多