39
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-07-20

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でローカルのタイムゾーンを変更してしまいます。

var Local *Location = &localLoc

> Local represents the system's local time zone. 

```go
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はタイムゾーンが考慮されていません。他にも同様のメソッドがあるかもしれませんので、時間が正しい事の確認は確実に行ってください。

39
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?