Tag Archives: ruby

Use DateTime instead of Date for ActiveRecord ranges

I was working with a query that selected all “Orders” created this month, it looked like this:

@today = Time.zone.now.to_date
@start_date = @today.beginning_of_month
@end_date = @today.end_of_month
@orders = Order.where(created_at: @start_date..@end_date)

and the resulting SQL query looked like this:

SELECT `orders`.* FROM `orders` WHERE (`orders`.`created_at` BETWEEN '2014-08-01' AND '2014-08-31')

…but since Rails automatically converts Date objects from localtime to UTC the dates in that query should have been offset by my timezone (in this case PDT -7 hours).

The fix was simple, use DateTime objects instead of Date objects and Rails automatically calculated the offset based on my Timezone (config.time_zone):

@today = Time.zone.now.to_datetime
# ...

and the fixed query:

SELECT `orders`.* FROM `orders` WHERE (`orders`.`created_at` BETWEEN '2014-08-01 07:00:00' AND '2014-09-01 06:59:59')