LoginSignup
4
0

More than 1 year has passed since last update.

Goでの日付比較チートシート

Last updated at Posted at 2022-12-22

概要

Goで日時を司る型はtime.Timeでナノ秒まで適用される。
このtime.Timeには比較演算子の==, <, >が使えずAfter, Before, Equalメソッドを使って比較する必要がある。

チートシート

時間の関係 記述 返値
a > b a.After(b) true
a > b a.Equal(b) false
a > b a.Before(b) false
a = b a.After(b) false
a = b a.Equal(b) true
a = b a.Before(b) false
a < b a.After(b) false
a < b a.Equal(b) false
a < b a.Before(b) true

ポイント

time.TimeのAfter、Beforeはイコールを含まない評価をするようになっています。
そのため a <= btrue を返す、つまりイコールを含むような評価をしたい場合は以下の2パターンで記述する。

  1. a.Before(b) || a.Equal(b)
  2. !a.After(b)

個人的には2パターン目が短くてif文に含める時にはよく見ると思います。

4
0
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
4
0