时间比较的意外行为

时间:2014-07-30 20:31:30

标签: ruby-on-rails postgresql model

好的,所以我有一个26天前创建的记录,但是当我与2.days.ago进行比较时,它告诉我错误我不知道为什么,我已经在这里等了3个小时尝试了几个事情和做很多谷歌搜索似乎没有任何作用 这是我的终端代码示例

  

2.1.1 :066 > Ticket4Midnite.first.created_at Ticket4Midnite Load (0.3ms) SELECT "ticket4_midnites".* FROM "ticket4_midnites" LIMIT 1 => Fri, 04 Jul 2014 19:10:00 UTC +00:00 2.1.1 :067 > helper.time_ago_in_words(Ticket4Midnite.first.created_at) Ticket4Midnite Load (0.3ms) SELECT "ticket4_midnites".* FROM "ticket4_midnites" LIMIT 1 => "26 days" 2.1.1 :068 > Ticket4Midnite.first.created_at>=2.days.ago Ticket4Midnite Load (0.3ms) SELECT "ticket4_midnites".* FROM "ticket4_midnites" LIMIT 1 => false 2.1.1 :069 >

我的表数据类型的示例我正在使用postgresql数据库

  

Table "public.ticket4_midnites" Column | Type | Modifiers ---------------------------+-----------------------------+--------------------------------------------------------------- id | integer | not null default nextval('ticket4_midnites_id_seq'::regclass) company | character varying(255) | surfaceLocation | character varying(255) | DownholeLocation | character varying(255) | Field | character varying(255) | SiteSupervisor | character varying(255) | SafeWorkPermit | character varying(255) | Date | character varying(255) | DayNightTour | character varying(255) | RigNumber | character varying(255) | ReportNumber | character varying(255) | returnToBase | boolean | StayinCamp | boolean | prejobsafety | boolean | rigWalkAroundDone | boolean | AirKillSafetyCheck | boolean | FunctionTestBOP | boolean | DrillHeadwhileTappingRods | boolean | BOPDrillSatisfactory | boolean | created_at | timestamp without time zone | not null updated_at | timestamp without time zone | not null username | character varying(255) | status | character varying(255) | Indexes: "ticket4_midnites_pkey" PRIMARY KEY, btree (id)

如果您需要任何其他信息,我将提供任何帮助将不胜感激!!

1 个答案:

答案 0 :(得分:1)

像弗雷德里克·张在评论中指出的那样,你误解了Ticket4Midnite.first.created_at>=2.days.ago的作用。

通过拆分代码,您可以看到它实际上在做什么 看看它是这样的:

(Ticket4Midnite.first.created_at) >= (2.days.ago)

这只是比较时间戳。

(July 4th @ Some time) >= (July 28th @ current time)

这是问第一个时间戳是否比两天前更早的时间。

由于它不是,它会返回false

另一个例子,来自ruby-docs for Time

t1 = Time.new(2010)
t2 = Time.new(2011)

t1 == t2 #=> false
t1 == t1 #=> true
t1 <  t2 #=> true
t1 >  t2 #=> false

大于和小于时间的比较是在问哪个时间是第一次。

因此,对于您的情况,只需翻转比较的方向,它就会按预期运行。