LoginSignup
3
5

More than 5 years have passed since last update.

golangのtimeパッケージで「〜以前」「〜以降」

Last updated at Posted at 2017-06-30

はじめに

まず、 time パッケージの Time.Before(Time) および Time.After(Time) メソッドを見てみると、Less Than および More Than になっています。

// After reports whether the time instant t is after u.
func (t Time) After(u Time) bool {
    return t.sec > u.sec || t.sec == u.sec && t.nsec > u.nsec
}

// Before reports whether the time instant t is before u.
func (t Time) Before(u Time) bool {
    return t.sec < u.sec || t.sec == u.sec && t.nsec < u.nsec
}

つまり、 Time.Before(Time) および Time.After(Time) は「〜より前」「〜より後」であり、入力引数の時刻は含まれません。

対して、Less Than or Equal または More Than or Equal 、すなわち「〜以降」「〜以前」を表現したい場合にはどうすればよいでしょうか。

方法

答えは簡単。 NOT をとるだけ。

if t1.Before(t2) {
    // t2.After(t1) でも同じ
    fmt.Println("t1 < t2")
}

if !t1.After(t2) {
    // !t2.Before(t1) でも同じ
    fmt.Println("t1 <= t2")
}

3
5
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
3
5