Date / Time
time.Time: 同じ瞬間でも==とEqualは異なる
==はlocationなどの内部表現も比較しますが、Equalは同じ時点を表すか比較します。
Sourceequal.go
Go 1.22
package timevalue
import "time"
func CompareSameInstant() (directEqual bool, instantEqual bool) {
utc := time.Date(2026, time.August, 27, 0, 0, 0, 0, time.UTC)
jst := utc.In(time.FixedZone("JST", 9*60*60))
return utc == jst, utc.Equal(jst)
}Testequal_test.go
Go 1.22
package timevalue
import "testing"
func Test同じ時刻でもlocationが異なるtimeTimeはEqualと比較結果が異なる(t *testing.T) {
directEqual, instantEqual := CompareSameInstant()
if directEqual || !instantEqual {
t.Fatalf("directEqual = %t, instantEqual = %t", directEqual, instantEqual)
}
}01Assertion
このテストで確認できること
- UTCとJSTのtime.Timeは==ではfalseになる
- 同じ瞬間ならEqualではtrueになる
永続化・API・タイムゾーン変換をまたぐ時刻の比較ではtime.Timeの==を避け、意図が瞬間比較ならEqualを使います。
OBSERVED RESULT
utc == jst → false
utc.Equal(jst) → true