8
4

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での time.Location のあれこれ

Posted at

time.LoadLocation()

それぞれのタイムゾーン情報は、以下のようにして取得できる。

package main

import (
	"fmt"
	"time"
)

func main() {
	utc, _ := time.LoadLocation("UTC")
	fmt.Println(utc.String())
	fmt.Println(time.Now().In(utc))

	jst, _ := time.LoadLocation("Asia/Tokyo")
	fmt.Println(jst.String())
	fmt.Println(time.Now().In(jst))
}
$ go run main.go
UTC
2017-01-07 07:07:11.411502827 +0000 UTC
Asia/Tokyo
2017-01-07 16:07:11.411913577 +0900 JST

ローカルタイムゾーン

サーバーのローカルタイムゾーン情報は、
以下のように明示的にタイムゾーン名を指定せずに、"Local" を引数とすると取得できる。

package main

import (
	"fmt"
	"time"
)

func main() {
	local, _ := time.LoadLocation("Local")
	fmt.Println(local.String())
}
$ go run main.go
Local

ちなみに、以下のように空文字列を引数とすると、UTCが返ってくる。

package main

import (
    "fmt"
    "time"
)

func main() {
    utc, _ := time.LoadLocation("")
    fmt.Println(utc.String())
}
$ go run main.go
UTC

なお、LoadLocation() を使わずに、

  • サーバーのタイムゾーン
  • UTC

には直接アクセスすることも出来る。

package main

import (
	"fmt"
	"time"
)

func main() {
	utc := time.UTC
	fmt.Println(utc.String())

	local := time.Local
	fmt.Println(local.String())
}
$ go run main.go
UTC
Local
8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?