golang: time.LoadLocation("Europe/Moscow") выдает ошибку, где я ошибся?

Рейтинг: 1Ответов: 2Опубликовано: 28.06.2023

Есть такой код:

func main() {
    fmt.Println(isWorkingHours())
}

func isWorkingHours() (bool, error) {
    location, err := time.LoadLocation("Europe/Moscow")
    if err != nil {
        return false, err
    }
    now := time.Now().In(location)
    if now.Weekday() == time.Sunday || now.Weekday() == time.Saturday {
        return false, nil
    }
    if now.Hour() < 10 || now.Hour() > 19 {
        return false, nil
    }
    return true, nil
}

Он работает в Playground https://go.dev/play/p/BMwcZynMbdn?v=goprev, но локально отдает nil, unknown time zone Europe/Moscow

Не могу понять почему?

Docker: golang:1.19-alpine

Ответы

▲ 2Принят

Нужно было добавить _ "time/tzdata"

▲ 0

https://lalatron.hashnode.dev/a-story-about-go-docker-and-time-zones

How to fix it? First, let's see where our Go app retrieves the time zone information from. Time to peek into the time package. You can find here info on all environments, but below you can check where the time zone info is in Unix systems.

/src/time/zoneinfo_unix.go:21

// Many systems use /usr/share/zoneinfo, Solaris 2 has
// /usr/share/lib/zoneinfo, IRIX 6 has /usr/lib/locale/TZ.
var zoneSources = []string{
    "/usr/share/zoneinfo/",
    "/usr/share/lib/zoneinfo/",
    "/usr/lib/locale/TZ/",
    runtime.GOROOT() + "/lib/time/zoneinfo.zip",
}

For this approach, there are two things to do to get the time zone info data available at runtime.

Copy the time zone info from the build image Update the ZONEINFO environment variable with the correct path to the zoneinfo.zip file

FROM golang:1.14-alpine
WORKDIR /app
ADD . .
RUN CGO_ENABLED=0 GOOS=linux go build -o myapp

FROM scratch
COPY --from=0 /app/myapp .
COPY --from=0 /usr/local/go/lib/time/zoneinfo.zip /
ENV ZONEINFO=/zoneinfo.zip
CMD ["/myapp"]