Golang: Time.In panic missing Location
Mon, Apr 8, 2024
One-minute read
Golang: Time.In panic missing Location
This worked fine in development on my machine.
func isToday(d Date) bool {
t := time.Now().UTC()
tz := "Australia/Brisbane"
localTZ, err := time.LoadLocation(tz)
if err != nil {
slog.Error("timezone", "error", err)
t = t.In(localTZ)
}
if d.DayMonth.Day() == t.Day() && d.DayMonth.Month() == t.Month() {
slog.Info("date match", "date", d.DayMonth, "tz", tz)
return true
}
return false
}
But in production produced:
2024-04-08T08:33:35Z 2024/04/08 08:33:35 ERROR timezone error="unknown time zone Australia/Brisbane"
2024-04-08T08:33:35Z 2024/04/08 08:33:35 http: panic serving 127.0.0.1:46164: time: missing Location in call to Time.In
Turns out, if Go can’t retrieve timezones from the machine it’ll panic. You can force Go
to embed timezones into the application though by importing time/tzdata
.
import _ "time/tzdata"
func isToday(d Date) bool {
t := time.Now().UTC()
tz := "Australia/Brisbane"
localTZ, err := time.LoadLocation(tz)
if err != nil {
slog.Error("timezone", "error", err)
t = t.In(localTZ)
}
if d.DayMonth.Day() == t.Day() && d.DayMonth.Month() == t.Month() {
slog.Info("date match", "date", d.DayMonth, "tz", tz)
return true
}
return false
}
Now it works!
Tags:
#TIL #time #go