登录
首页 >  Golang >  Go问答

OpenWRT中Golang的time.Now()为何返回UTC时间?

来源:stackoverflow

时间:2024-03-23 22:30:36 458浏览 收藏

在 OpenWRT 中使用 Go 语言的 `time.Now()` 函数时,它返回 UTC 时间而不是本地时间。这是因为 OpenWRT 缺少 `zoneinfo` 包,该包提供时区信息。如果没有此包,Go 语言将使用 `/etc/localtime` 指向的时区,该时区可能未正确设置。为了解决此问题,需要安装 `zoneinfo` 包,并确保在 `/etc/config/system` 中设置正确的时区。

问题内容

我编写了一个在 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() 获取正确的当地时间?


解决方案


我的问题的根源是我的 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。最后,我可以获得正确的时间。now()。

openwrt 将时区存储在名为 /etc/tz 的文件中。如果此文件丢失或为空,openwrt 假定本地时间等于 utc 时间。 Source

Specifying the Time Zone with TZ

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

到这里,我们也就讲完了《OpenWRT中Golang的time.Now()为何返回UTC时间?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>