DEV Community

KOGA Mitsuhiro
KOGA Mitsuhiro

Posted on • Originally published at qiita.com

Goでローカルのタイムゾーンを設定する

#go

Goでタイムゾーンを変えたい場合はfunc (Time) Inを使います。

package main

import "time"

const location = "Asia/Tokyo"

func main() {
    loc, err := time.LoadLocation(location)
    if err != nil {
        loc = time.FixedZone(location, 9*60*60)
    }
    now := time.Now().In(loc)
}

このようにタイムゾーンを変更したい処理が一箇所ならいいのですが、複数あると面倒な上に変更漏れがあるとバグの原因を見付けるのが大変です。そんな時はtime.Localでローカルのタイムゾーンを変更してしまいます。

http://golang.org/pkg/time/#Location

var Local *Location = &localLoc

Local represents the system's local time zone.

package main

import "time"

const location = "Asia/Tokyo"

func init() {
    loc, err := time.LoadLocation(location)
    if err != nil {
        loc = time.FixedZone(location, 9*60*60)
    }
    time.Local = loc
}

func main() {
    now := time.Now()
}

ただし、time.Timeから日付だけを取り出すで指摘されているようにfunc (Time) Truncateはタイムゾーンが考慮されていません。他にも同様のメソッドがあるかもしれませんので、時間が正しい事の確認は確実に行ってください。

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay