doushifen4060 2019-01-04 08:26
浏览 895
已采纳

为什么在OpenWRT上运行Golang的time.Now()总是获得UTC时间?

I wrote a Golang program that runs on OpenWRT.

package main

import (
    "fmt"
    "time"
)

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

When I run this program on my Macbook, I always get the correct local time.

However, when running this program on OpenWRT, I always get UTC time.

I have set the time zone and time of OpenWRT. When I execute uci show system, I can see the right time zone. When I execute date the right local time can be display correctly.

So my question is, how do I get the correct local time using Golang's time.Now() on OpenWRT?

  • 写回答

2条回答 默认 最新

  • dsvcqvp139098 2019-01-04 10:10
    关注

    The root of my problem is that my OpenWRT lacks the zoneinfo package. So I run opkg update && opkg install zoneinfo-xxx first.

    This is part of 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.
    
        ...
    
    }
    

    According to this file, if there is no "TZ" variable, Golang will use the time zone pointed to by /etc/localtime when calling time.Now().

    Then I set time zone at /etc/config/system (option zonename 'xxxxxx') and run /etc/init.d/system restart. Finally, I can get the correct time.Now().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵