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

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of DataStax

Langflow: Simplify AI Agent Building

Connect models, vector stores, memory and other AI building blocks with the click of a button to build and deploy AI-powered agents.

Get started for free

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay