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

我编写了一个在OpenWRT上运行的Golang程序。</ p>

  包main 

import(
“ fmt”
“ time”

func main(){
fmt.Println(time.Now())
}
</ code> < / pre>

当我在Macbook上运行该程序时,我总是得到正确的本地时间。</ p>

但是,在OpenWRT上运行此程序时,我总是得到 UTC时间。</ p>

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

所以我的问题是,如何使用Golang的时间获取正确的本地时间。 )在OpenWRT上?</ p>
</ div>

展开原文

原文

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?

dongyaofu0599
dongyaofu0599 谢谢。这正是我所需要的。
一年多之前 回复
dpvomqeu396484
dpvomqeu396484 不确定是否有帮助,但这是如何确定类似Unix的系统上的本地时区的方法。
一年多之前 回复

2个回答

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().



OpenWRT将时区存储在名为/ etc / TZ的文件中。 如果此文件丢失或为空,则OpenWRT假定本地时间等于UTC时间。 来源 </ p>


如何
OpenWRT上使用Golang的time.Now()获取正确的本地时间?</ p>
</ blockquote>

使用TZ指定时区 </ p>

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

展开原文

原文

OpenWRT stores the time zone inside a file named /etc/TZ. If this file is missing or empty, OpenWRT assumes the local time equals UTC time. Source

how do I get the correct local time using Golang's time.Now() on OpenWRT?

Specifying the Time Zone with TZ

The is the value you must add to or substract from the local time to get the UTC time. This offset will be positive if the local time zone is west of the Prime Meridian and negative if it is east.

dream3323
dream3323 谢谢您的回复! 我通过安装zoneinfo软件包并在/ etc / config / system中设置选项zonename来解决此问题。
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐