2015-04-07 81 views
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)属于同一班级,看起来相同,但不相等。请分享您的观点并帮助我解决此问题。

回答

0

time1time2是彩车的to_f输出应该显示他们是不相等

+0

但有其他的方法,使他们平等的吗?其实我的要求是发起一个查询,例如User.where(:created_at.gt => time1)。在这种情况下,我不能使用:created_at.gt.to_f。请给我一些其他建议。 – user2289433

+0

在比较它们之前使用'to_i'或'to_s' – sicks

+0

但是您认为User.where(:created_at.gt.to_i => time1)会起作用吗?它不工作。 – user2289433