[rspec-users] Date comparisons

Scott Taylor mailing_lists at railsnewbie.com
Sat May 3 16:53:42 EDT 2008


On May 3, 2008, at 2:16 PM, Kyle Hargraves wrote:

> On Sat, May 3, 2008 at 1:12 PM, Steve Downey  
> <steve.downtown at gmail.com> wrote:
>> Is there more precision than seconds in a Time instance?
>>
>> irb(main):006:0> a,b = Time.now, Time.now
>> => [Sat May 03 11:06:31 -0700 2008, Sat May 03 11:06:31 -0700 2008]
>> irb(main):007:0> puts a.to_i, b.to_i
>> 1209837991
>> 1209837991
>> => nil
>
> This came up this morning in #rspec; Time tracks microseconds which
> blows up equality:
>
>>> a, b = Time.now, Time.now
> => [Sat May 03 13:15:31 -0500 2008, Sat May 03 13:15:31 -0500 2008]
>>> a == b
> => false
>>> [a.usec, b.usec]
> => [93308, 93309]
>
> Because of this, I tend to use 'should be_between()' when handling
> times; someone else suggested the .to_i trick which is probably closer
> to what is intended, but for some reason I find it confusing.

If I'm in a rails project, I like to use to_s(:db) to compare the  
times - that's how they are stored in the database.  Any greater  
precision (at least in MySQL) gets lost when the datetime is read out  
of the database.

Scott



More information about the rspec-users mailing list