在工作曾遇到一個問題
time1 = Time.current
time2 = Time.zone.today.advance(days: -7).end_of_week
time1 > time2
# => true
time2 > time1
# => ArgumentError: comparison of Date with ActiveSupport::TimeWithZone failed
(Rails 6 有解決了)
因為我們公司是用Rails 3,我想說兩個時間物件,怎麼會一下子可以比大小,不過換個順序就不行了?
原來:
Time.current.class
# => ActiveSupport::TimeWithZone
Time.zone.today.advance(days: -7).end_of_week.class
# => Date
一個是 Rails 類別 ActiveSupport::TimeWithZone
一個是 Ruby 類別 Date
在Rails 3,Date類別的:>
方法可比較類別沒有 ActiveSupport::TimeWithZone。但是 TimeWithZone 的可比較類別有Date,也就是遇到Date類別,TimeWithZone會幫他自動轉換。
使用:to_datetime
方法,都轉成 DateTime 物件
time1 = Time.current
# => Tue, 22 Sep 2020 15:49:55 UTC +00:00
time1.to_datetime
# => Tue, 22 Sep 2020 15:49:55 +0000
time1.to_datetime.class
=> DateTime
time2 = Time.zone.today.advance(days: -7).end_of_week
# => Sun, 20 Sep 2020
time2.to_datetime
# => Sun, 20 Sep 2020 00:00:00 +0000
time2.to_datetime.class
# => DateTime
time2 > time1
# => false
總算可以將兩個時間作比較了