LoginSignup
49
22

More than 5 years have passed since last update.

go の日時比較 timeパケージで「以上」「以下」はどうやって比較するの?

Last updated at Posted at 2015-03-02

たぶんこう
    old := time.Now().Add(-time.Second)
    now := time.Now()

    if old.Equal(now) || old.Before(now) {  // old <= now 
    }
    if now.Equal(old) || now.After(old) {   // now >= old
    }

たぶんこれなんだろうけど、なんかイマイチですよね。。

コメントで正解を頂きました。

これが正解

    if !old.After(now) {    // old <= now --- ! old > now
    }
    if !now.Before(old) {   // now >= old --- ! now < old
    }

しかし、頭が悪い私には直感的ではないのは変わらないので、
Unix timeに変換してから比較する案もありかなと。

unixTimeにしてみる
    if now.Unix() >= old.Unix() {
    }
    if old.Unix() <= now.Unix() {
    }

もう日時比較は常にunix timeでいいじゃ?
nano秒単位で比較したい場合は、UnixNano()を使えばいいし。

というわけでベンチしてみました。

MacBook Pro (Retina, Mid 2012)

$ go version
go version go1.4.1 darwin/amd64
$ go test -bench .
testing: warning: no tests to run
PASS
BenchmarkTimeAfter  2000000000           1.10 ns/op
BenchmarkTimeBefore 2000000000           1.07 ns/op
BenchmarkTimeUnixAfter  2000000000           1.22 ns/op
BenchmarkTimeUnixBefore 2000000000           1.23 ns/op
BenchmarkTimeUnixNanoAfter  2000000000           1.86 ns/op
BenchmarkTimeUnixNanoBefore 2000000000           1.87 ns/op
BenchmarkTimeEqualAfter 1000000000           2.11 ns/op
BenchmarkTimeEqualBefore    1000000000           2.15 ns/op
BenchmarkTimeAfterEqual 2000000000           1.25 ns/op
BenchmarkTimeBeforeEqual    2000000000           1.20 ns/op
BenchmarkTimeUnixAfterEqual 2000000000           1.21 ns/op
BenchmarkTimeUnixBeforeEqual    2000000000           1.22 ns/op
BenchmarkTimeUnixNanoAfterEqual 2000000000           1.80 ns/op
BenchmarkTimeUnixNanoBeforeEqual    2000000000           1.85 ns/op
ok      github.com/masahide/test/t  40.183s

やっぱりAfter(),Before()が最速です。
しかし「以上」「以下」になると、
比較順によりますが、Unix()をつかった比較と同じぐらいになりますね。
というわけで、time.Second精度での比較であれば
Unix()で比較演算子を使うのもありな気がしました。

あとでベンチやり直します。。

49
22
2

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
49
22