Skip to main content
Version: 2.8.x(Latest)

SetTimeZone Setting Global Time Zone

package main

import (
"fmt"
"time"

"github.com/gogf/gf/v2/os/gtime"
)

func main() {
// Set the global time zone for the process
err := gtime.SetTimeZone("Asia/Tokyo")
if err != nil {
panic(err)
}

// Use gtime to get the current time
fmt.Println(gtime.Now().String())

// Use standard library to get the current time
fmt.Println(time.Now().String())
}

After execution, the output result is:

2023-01-06 15:27:38
2023-01-06 15:27:38.753909 +0900 JST m=+0.002758145

Time Zone Settings Precautions

SetTimeZone Method Multiple Calls Error

The SetTimeZone method allows setting the global time zone only once. If called multiple times with different time zones, subsequent calls will fail and return an error.

Initialization Issue with the time Package in Business Projects

The global setting of the program's time zone must be called before importing the standard library's time package, as it initializes upon import, preventing further global time zone changes. Time zone conversions on specific time objects can only be done using the ToLocation method (or the standard library's In method). An example of converting using ToLocation:

package main

import (
"fmt"
"time"

"github.com/gogf/gf/v2/os/gtime"
)

func main() {
// Set the global time zone for the process
err := gtime.SetTimeZone("Asia/Tokyo")
if err != nil {
panic(err)
}

// Use gtime to get the current time
fmt.Println(gtime.Now())

// Use standard library to get the current time
fmt.Println(time.Now())

// Perform time zone conversion on a specific time object
local, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
panic(err)
}
fmt.Println(gtime.Now().ToLocation(local))
}

After execution, the terminal outputs:

2023-01-06 15:37:38
2023-01-06 15:37:38.753909 +0900 JST m=+0.002758145
2023-01-06 14:37:38

In business projects, there are often many business packages import before the main package, which can cause initialization issues with the time package. Therefore, if you need to set the time zone globally, it is recommended to call the SetTimeZone method through an independent package and execute import at the very beginning of the main package to avoid initialization issues with the time package. For example:

Related reference link: https://stackoverflow.com/questions/54363451/setting-timezone-globally-in-golang

package main

import (
_ "boot/time"

"fmt"
"time"
)

func main() {
// Use gtime to get the current time
fmt.Println(gtime.Now().String())

// Use standard library to get the current time
fmt.Println(time.Now().String())
}