Software dev, tech, mind hacks and the occasional personal bit

Odd Date and Time Comparisons in Rails & Hack night

While comparing Dates and Times in Rails (both 2.3 and 3), I came across an odd behaviour:

>> Time.parse("Mon, 26 Jul 2010 9:59") == Date.new(2010, 7, 26)
=> false
>> Time.parse("Mon, 26 Jul 2010 10:00") == Date.new(2010, 7, 26)
=> true
>> Time.parse("Mon, 26 Jul 2010 10:01") == Date.new(2010, 7, 26)
=> false

Also

>> Date.new(2010, 7, 26) == Time.parse("Mon, 26 Jul 2010 10:00")
=> false (Rails 2.3)
=> nil (Rails 3)
>> Date.new(2010, 7, 26) == Time.parse("Mon, 26 Jul 2010 0:00")
=> false (Rails 2.3)
=> nil (Rails 3)

Tonight, we’ll be having the RORO hack night in the ThoughtWorks Sydney office, with a focus on open source projects (your own or contributing). A patch for this date/time behaviour might be an interesting area to pursue.

Previous

Ruby 1.8 Scoping and Blocks

Next

Rails Refactor & Hack Night

2 Comments

  1. Brian Egge

    When Time.Parse creates a Time object, it parses assuming the local time zone. So for you:

    Time.parse(“Mon, 26 Jul 2010 10:00”)
    => Mon Jul 26 10:00:00 +1000 2010

    But for me:
    Time.parse(“Mon, 26 Jul 2010 10:00”)
    => Mon Jul 26 10:00:00 -0400 2010

    In your case, 10am is 00:00 GMT. According to http://corelib.rubyonrails.org/classes/Date.html converting a date to a time causes it to assume midnight GMT as the time.

    Without Rails, you will get nil if you attempt to compare a Date and Time. When you load Rails it adds various extension methods, including new operators.

    Unfortunately, the implementation for time is wildly different than for date. This makes the comparison non-symmetric. It is difficult to create symmetric equals or comparison methods when you have objects of two different types.

  2. Hey Brian!

    Thanks for looking into this and explaining it so well 🙂

    It does seem like an inconsistent design choice though. Date always assumes GMT, but Time uses local – it would be much nicer to work with if they both took the same approach. Also, if symmetrical comparisons are not possible, perhaps it would be better to always return null, or raise an exception when comparing Date and Time. I came across this behaviour because I had unintentionally compared a date and a time leading to an odd bug that occurred only after 10am!

    Cheers,
    James

Powered by WordPress & Theme by Anders Norén