SetTimeZone Setting Global Time Zone

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gogf/gf/v2/os/gtime"
  6. )
  7. func main() {
  8. // Set the global time zone for the process
  9. err := gtime.SetTimeZone("Asia/Tokyo")
  10. if err != nil {
  11. panic(err)
  12. }
  13. // Use gtime to get the current time
  14. fmt.Println(gtime.Now().String())
  15. // Use standard library to get the current time
  16. fmt.Println(time.Now().String())
  17. }

After execution, the output result is:

  1. 2023-01-06 15:27:38
  2. 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:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gogf/gf/v2/os/gtime"
  6. )
  7. func main() {
  8. // Set the global time zone for the process
  9. err := gtime.SetTimeZone("Asia/Tokyo")
  10. if err != nil {
  11. panic(err)
  12. }
  13. // Use gtime to get the current time
  14. fmt.Println(gtime.Now())
  15. // Use standard library to get the current time
  16. fmt.Println(time.Now())
  17. // Perform time zone conversion on a specific time object
  18. local, err := time.LoadLocation("Asia/Shanghai")
  19. if err != nil {
  20. panic(err)
  21. }
  22. fmt.Println(gtime.Now().ToLocation(local))
  23. }

After execution, the terminal outputs:

  1. 2023-01-06 15:37:38
  2. 2023-01-06 15:37:38.753909 +0900 JST m=+0.002758145
  3. 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

  1. package main
  2. import (
  3. _ "boot/time"
  4. "fmt"
  5. "time"
  6. )
  7. func main() {
  8. // Use gtime to get the current time
  9. fmt.Println(gtime.Now().String())
  10. // Use standard library to get the current time
  11. fmt.Println(time.Now().String())
  12. }