You can set to váriavél time.Local
. According to the documentation:
var Local *Location = &localLoc
Local represents the system’s local time zone. On Unix systems, Local > consults the TZ Environment variable to find the time zone to use. No > TZ Means use the system default /etc/localtime. TZ="" Means use UTC. > TZ="foo" Means use file foo in the system Timezone directory.
Then you can use to change the Location.
For example:
time.Local = time.UTC
Thus in executing the time.Now()
will be in UTC.
In the case of America/Sao_Paulo
just do:
time.Local, _ = time.LoadLocation("America/Sao_Paulo")
This can be stated in main()
and all subsequent calls will use that time zone.
If you take a test:
func main() {
fmt.Println("Tempo padrão:", time.Now())
time.Local = time.UTC
fmt.Println("Tempo UTC:", time.Now())
fmt.Println("Tempo UTC:", time.Now())
time.Local, _ = time.LoadLocation("America/Sao_Paulo")
fmt.Println("Tempo SP:", time.Now())
fmt.Println("Tempo SP:", time.Now())
}
Upshot:
Tempo padrão: 2021-06-17 15:28:04.5675042 +0100 BST m=+0.092369601
Tempo UTC: 2021-06-17 14:28:04.5844768 +0000 UTC m=+0.109342201
Tempo UTC: 2021-06-17 14:28:04.5844768 +0000 UTC m=+0.109342201
Tempo SP: 2021-06-17 11:28:04.5844768 -0300 -03 m=+0.109342201
Tempo SP: 2021-06-17 11:28:04.5844768 -0300 -03 m=+0.109342201
Ball show! It worked perfectly! Can you tell me if there has always been this variable? Because years ago when I researched I found nothing.
– Eduardo Mior
It has always existed, at least since Go 1.0.1, there from ~2012. You can see the source code at https://go.googlesource.com/go/+/refs/tags/go1.0.1/src/pkg/time/zoneinfo.go#57.
– Inkeliz
I get it. Strange that when I researched I didn’t find this anywhere, and I researched a lot, very much, then as I didn’t find anything at the time I ended up creating a function that initializes a new team.time in the Timezone that I want. But this way ai is simpler and is native to GO. Thank you again.
– Eduardo Mior