brafales
brafales

Reputation: 590

Ruby DateTime comparison problem

I'm implementing a validation method for a model that checks that an expiration date is not before the publication date. I tried with this

def valid_date_interval
  if self.expired_at && self.published_at
    errors.add(:published_at, I18n.t('ubiquo.highlight.error_invalid_interval')) if self.expired_at <= self.published_at
  end
end

However I'm having results that make no sense to me when comparing the two datetimes. Two DateTimes thar are the same time get compared to false. Here's some irb code:

(rdb:1) p self.published_at.to_i == self.expired_at.to_i
true
(rdb:1) p self.published_at.to_i == self.expired_at.to_i + 1
false
(rdb:1) p self.published_at == self.expired_at
false
(rdb:1) p self
#<Highlight id: nil, title: "MyString", published_at: "2011-06-02 10:22:05", expired_at: "2011-06-02 10:22:05", created_at: nil, updated_at: nil, program_id: 827572094>

Anyone could enlighten me in how those comparisons work?

Cheers!

Upvotes: 0

Views: 1409

Answers (1)

steenslag
steenslag

Reputation: 80065

Probably self.published_at.nsec is not equal to self.expired_at.nsec . (nsec returns the nanoseconds). See the doc for <=>.

Upvotes: 2

Related Questions