问题描述

我正在尝试为我的应用程序修改golang时区

I'm trying to modify golang timezone for my application

我看过 time 包,初始化时区发生在

I have took a look at time package, initializing timezone happens in

time/zoneinfo_unix.go @ initLocal

time/zoneinfo_unix.go @ initLocal

TZ
TZ
/etc/localtimeUTC
/etc/localtimeUTC

到目前为止我尝试过的

1-效果很好-但我不想使用任何一种方法-:

1- works fine -But i don't want to use either of those approaches - :

TZ = Africa/Cairo$ export TZ = Africa/Cairo
TZ = Africa/Cairo$ export TZ = Africa/Cairo

2-没用

  • 在我的应用程序初始化中(应用程序初始化在一个单独的程序包中,该程序包已在主程序中导入),我使用os.SetEnv("TZ","Africa/Cairo")

当我简化主程序并使用os.SetEnv("TZ","Africa/Cairo")而不导入除"os-time"以外的任何其他软件包时,它将按预期工作

When i simplify the main and use os.SetEnv("TZ", "Africa/Cairo") without importing any other packages other than "os - time" it works as expected

关于如何使第二种方法起作用的任何想法吗?

Any ideas about how to make the second approache work ?

Docker映像:golang:1.11.2

Docker image: golang:1.11.2

推荐答案

os.Setenv("TZ", "Africa/Cairo")
os.Setenv("TZ", "Africa/Cairo")time

如何确保?创建一个除了设置时区外不执行其他操作的程序包(以后您可以在其中添加其他内容,但是对于我们的示例来说就足够了).

How to ensure that? Create a package that does nothing else except sets the timezone (later you may add other things to it, but for our example that's enough).

赞:

package tzinit

import (
    "os"
)

func init() {
    os.Setenv("TZ", "Africa/Cairo")
}
tzinitmain
tzinitmain
package main

import _ "path/to/tzinit"

// Your other, "regular" imports:
import (
    "fmt"
    "os"
    "time"
    ...
)
TZtime
TZtime
tzinitimporttzinit
importtzinittzinit

警告语.

main
main

为确保可重现的初始化行为,鼓励构建系统以词法文件名的顺序向编译器提供属于同一软件包的多个文件.

To ensure reproducible initialization behavior, build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler.

TZ
TZ

这篇关于在Golang中全局设置时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!