0
請各位看看下面代碼 -比較後沒有工作的罰款
#rails default time
2.1.4 :101 > time1 = User.first.created_at
=> Mon, 19 Jan 2015 14:23:49 UTC +00:00
2.1.4 :102 > time1.class
=> ActiveSupport::TimeWithZone
#convert time into timestamp
2.1.4 :103 > time1.to_i
=> 1421677429
2.1.4 :104 > timestamp = User.first.created_at.to_i
=> 1421677429
#convert same timestamp again into datetime
2.1.4 :106 > DateTime.strptime(timestamp.to_s,'%s')
=> Mon, 19 Jan 2015 14:23:49 +0000
2.1.4 :107 > DateTime.strptime(timestamp.to_s,'%s').class
=> DateTime
#Convert time into timezone and comparing the time
2.1.4 :112 > time2 = DateTime.strptime(timestamp.to_s,'%s').in_time_zone
=> Mon, 19 Jan 2015 14:23:49 UTC +00:00
2.1.4 :118 > time1
=> Mon, 19 Jan 2015 14:23:49 UTC +00:00
2.1.4 :119 > time2
=> Mon, 19 Jan 2015 14:23:49 UTC +00:00
2.1.4 :120 > time1.class
=> ActiveSupport::TimeWithZone
2.1.4 :121 > time2.class
=> ActiveSupport::TimeWithZone
2.1.4 :122 > time1 == time2
=> false
2.1.4 :124 > time1 > time2
=> true
我只是想知道的是爲什麼這happenns?由於時間(時間1和時間2)屬於同一班級,看起來相同,但不相等。請分享您的觀點並幫助我解決此問題。
但有其他的方法,使他們平等的嗎?其實我的要求是發起一個查詢,例如User.where(:created_at.gt => time1)。在這種情況下,我不能使用:created_at.gt.to_f。請給我一些其他建議。 – user2289433
在比較它們之前使用'to_i'或'to_s' – sicks
但是您認爲User.where(:created_at.gt.to_i => time1)會起作用嗎?它不工作。 – user2289433