LoginSignup
69
55

More than 5 years have passed since last update.

Swift3で日付(Date)の比較が超簡単になっていた件

Last updated at Posted at 2017-05-24

これまで日付、Dateの比較ってすごく面倒だし、わかりにくかったです。

Swift
let today : Date = Date()
let yesterday: Date = Date(timeIntervalSinceNow:-60*60*24)

if today.compare(yesterday) == ComparisonResult.orderedDescending {
   print("今日は昨日よりも未来")  // 実行される
}

正直、orderedDescendingとかorderedAscendingってどっちがどっちだっけ…といつも迷っていました。

ですが、Swift3から新しく追加されたDate型であれば、比較演算子で比較ができるのです。
本当に嬉しい。

Swift
let now : Date = Date()
let yesterday: Date = Date(timeIntervalSinceNow: -60*60*24)
let tomorrow: Date = Date(timeIntervalSinceNow: 60*60*24)
let anotherNow : Date = Date()
let otherNow : Date = now

if tomorrow > now {
   print("tomorrowはnowよりも未来")  // 実行される
}
if tomorrow != now {
   print("tomorrowとnowは違う日")  // 実行される
}
if yesterday > now {
   print("yesterdayはnowよりも未来")  // 実行されない
}
if yesterday < now {
   print("yesterdayはnowよりも過去")  // 実行される
}
if now == anotherNow {
   print("nowとanotherNowは同じ")  // 実行されない
}
if now == otherNow {
   print("nowとotherNowは同じ")  // 実行される
}
if now <= anotherNow {
   print("nowはanotherNowよりもちょっとだけ未来")  // 実行される
}

上記でnowanotherNowは同じように見えますが、anotherNownowよりも後に実行されています。
この数行のコード間の数ミクロン秒の差があるので、nowanotherNowは同じではないということですね。

あぁ、嬉しい。
(今更かよ!って思われるかもしれませんが、、、)

69
55
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
69
55