time.Timeのゼロ値はUnixtimeのゼロじゃない
time.Timeのゼロ値はUnixtimeのゼロではないことを知り、備忘録。
まとめ
以下のコードだと、tにはUnixtimeとしてのゼロは入らない。
t := time.Time{} fmt.Println(t.UnixNano() == 0) // -> false
time.Unix()関数で2引数に0を指定すると、Unixtimeとしてのゼロが入る。
t := time.Unix(0, 0) fmt.Println(t.UnixNano() == 0) // -> true
time.Time{}とtime.Unix(0,0)
time.Time{}とtime.Unix(0,0)で得られるそれぞれの時刻とUnixtimeを以下に纏めた。time.Timeのゼロ値は西暦基準で、Unixtime基準ではない。このゼロ値をUnixtime[ナノ秒]にすると、過去の時刻なので負数になる。
記述 | 出力 |
time.Unix(0, 0) | 1970-01-01 00:00:00 +0000 UTC |
time.Unix(0, 0).UnixNano() | 0 |
time.Time{} | 0001-01-01 00:00:00 +0000 UTC |
time.Time{}.UnixNano() | -6795364578871345152 |
サンプルコード:The Go Playground
リファレンス
改めてtimeパッケージの仕様を見たら、勿論ちゃんと記載されている。やはり仕様書はしっかり読むべき(自戒)
https://golang.org/pkg/time/#Time
The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. As this time is unlikely to come up in practice, the IsZero method gives a simple way of detecting a time that has not been initialized explicitly.