Tom Copeland's Recent Posts

RSS Feeds

« Rails gem download numbers | Main | Sphinx, Riddle, and will_paginate »

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d83451d3c069e20105372021b7970b

Listed below are links to weblogs that reference Rails, ActiveRecord, and time ranges:

Comments

Nice, didnt know u could use a range as a condition on a date column. I was always doing ["created_at BETWEEN % AND %", start_date, end_date]

btw, ActiveSupport provides beginning_of_month() and end_of_month() functions.

def beginning_to_end_of_month(date)
(date.beginning_of_month)..(date.end_of_month)
end

With my past SQL programming, I've got in the habit of aways doing something like

WHERE datefield >= '2009-01-01' AND datefield < '2009-02-01'

I haven't tried your code, but in your example, I suspect you may miss items posted after midnight on '2009-01-31' (pretty much the whole day of January 31st).

Using '2009-01-31 24:59:59' usually doesn't work either because of floating-point rounding errors.

@josh, oh, cool, didn't know about that, thanks!

@tony, here's the SQL that ActiveRecord generates:

SELECT *
FROM "revisions"
WHERE ("revisions"."created_at"
BETWEEN '2009-01-01' AND '2009-01-31')

I should try that to see if it misses any of those edge dates.

@Tom -- Yeah, the databases that I have used will interrupt that as:

BETWEEN '2009-01-01 00:00:00' AND '2009-01-31 00:00:00'

And since it looks like you are storing times as well, that's a problem.

The next thing people try is to append "23:59:59" to the end_date, but like I said above, because times are stored as floating-point numbers, you may still miss some records.

@tony, ah, cool, thanks for the note. Just added "+ 1.day" onto there, seems like that should do the trick then.

The comments to this entry are closed.