Tag Archives: How to Set Time Zone

How to Set Time Zone in Golang

About me

Article launch | my blog | welcome to pay attention

Go language time.Now () returns the local time zone

time.Now().Format("2006-01-02 15:04:05")

Time setting custom time zone

var cstSh, _ = time.LoadLocation("Asia/Shanghai") //ShangHai
fmt.Println("SH : ", time.Now().In(cstSh).Format("2006-01-02 15:04:05"))

There is a problem with load location. It depends on IANA time zone database (tzdata for short). Generally, Linux system has it, but windows system does not. Therefore, if the go environment is not installed in the windows system, an error will be reported by calling loadlocation.

The current solutions include:

1. We can put the tzdata file into our own program directory, and then let the time package load the time zone file from our own program directory.

The file directory can be set through the environment variable. In the main method:

os.Setenv("ZONEINFO", '/home/tz/data.zip')

Then call the loadlocation method.

Download tzdata

2. Use time zone mode recommended mode

var cstZone = time.FixedZone("CST", 8*3600)       // East 8 District
fmt.Println("SH : ", time.Now().In(cstZone).Format("2006-01-02 15:04:05"))

Global settings

If you want to set the global time zone configuration, what should you do?

main.go Add an initialization method (at the main function)

func initInMain() {
	var cstZone = time.FixedZone("CST", 8*3600) // East 8 District
	time.Local = cstZone
}

Assign the defined time zone instance to the time.Local

Recommended reading

Redis: a new open source charging tool

Star’s top engineer skill map on GitHub

Chinese programmers are most likely to send wrong words

Recommended! Markdown icon Index Website