Forum: Ruby on Rails date time comparison

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
10c122532c00465b809dbf9dc35806a7?d=identicon&s=25 Paolo Negri (Guest)
on 2007-06-14 15:07
(Received via mailing list)
Hi there

in RoR i can convert a Time into a Date object

t = Time.new
=> Thu Jun 14 14:00:46 BST 2007
d = Date.new(2007,06,03)
#<Date: 4908509/2,0,2299161>
t.to_date
=>  #<Date: 4908531/2,0,2299161>
d.to_time
=> Sun Jun 03 00:00:00 BST 2007

But I can not compare Date and Time object

t > d

ArgumentError: comparison of Time with Date failed

Now, am I shooting myself in the foot if I do something like

class Date
  alias oldcmp <=>
  def <=>(other)
    if other.respond_to? :to_date
      oldcmp(other.to_date)
    else
      oldcmp(other)
    end
  end
end

class Time
  alias oldcmp <=>
  def <=>(other)
    if other.respond_to? :to_time
      oldcmp(other.to_time)
    else
      oldcmp(other)
    end
  end
end

To allow comparison among Date and Time objects?

Thanks

Paolo
This topic is locked and can not be replied to.