Problem
OS: Windows.
When I distribute the executable file to other computers, they encounter the following problem when running it.
time: missing Location in call to Time.In
However, there are no issues when debugging the code on my own computer.
Later, I discovered that the problem was caused by the time.LoadLocation
function, which references runtime.GOROOT/lib/time/zoneinfo/zoneinfo.zip
gorootZoneSource(runtime.GOROOT()) gorootZoneSource. Therefore, if the runtime.GOROOT
on other computers is different from that of the developer or even nonexistent, it will cause problems.
Solution
Unzip %GOROOT%/lib/time/zoneinfo/zoneinfo.zip
, select the desired time zone file, and use embed
together with time.LoadLocationFromTZData
to obtain the data for that region.
Example
package main
import (
"embed"
"time"
)
//go:embed zoneInfo
var zoneInfoFS embed.FS // get it from GOROOT/lib/time/zoneInfo.zip
func getLocation(name string) (loc *time.Location) {
bs, err := zoneInfoFS.ReadFile("zoneInfo/" + name)
if err != nil {
panic(err)
}
loc, err = time.LoadLocationFromTZData(name, bs)
if err != nil {
panic(err)
}
return loc
}
func main() {
locTW := getLocation("Asia/Taipei")
locJPN := getLocation("Asia/Tokyo")
}
Directory Structure
-📜main.go
- 📂zoneInfo
- 📂Asia
- 📜Taipei
- 📜Tokyo
- ...
time.LoadLocation()
(in fact, don't ignore any errors). Also for UTC timezone use thetime.UTC
variable. – Fritzie