DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Find All Rows For A Certain Day; Count Days Between Two Dates

12.12.2007
| 5918 views |
  • submit to reddit
        
# Find all rows created on a certain day; Rails apparently has a built-in :db string format
self.find(:all, :conditions => ["created_at >= ? AND created_at <= ?", day.beginning_of_day.to_s(:db), day.end_of_day.to_s(:db)])

# Find number of days between two dates
def days_between_dates(first, last)
  (YMD(last) - YMD(first))
end

def YMD(date)
  date.to_date.to_s.gsub("-", "").to_i
end
    

Comments

Snippets Manager replied on Tue, 2009/08/04 - 4:35pm

my code contained a little bug as well (linked to daylight saving) this would work better: # Find number of days between two dates def days_between_dates(first, last) ((last.to_time(:utc) - first.to_time(:utc)) / (24*60*60)).to_i end

Snippets Manager replied on Tue, 2009/08/04 - 4:35pm

the code days_between_dates provided is buggy (it won't work if the dates are in different months). A possible & simpler alternative: # Find number of days between two dates def days_between_dates(first, last) ((last.to_time - first.to_time) / (24*60*60)).to_i end