rails 3 group by date a datetime column

Viewed 24304
Foo.group(:start_at).count(:id)

How I can group this by date ? the "start_at" column is an datetime column

3 Answers

This is another way to solve this if you manage different time zones. The idea is to add or substract the hours of your timezone:

hours_diff = Time.zone.now.time_zone.utc_offset/(60*60) rescue 0
hours_diff = hours_diff.to_i
date_group = "DATE(form_answers.created_at)"
if hours_diff > 0
  date_group = "DATE(DATE_ADD(form_answers.created_at, INTERVAL #{hours_diff} HOUR ))"
elsif hours_diff < 0
  date_group = "DATE(DATE_SUB(form_answers.created_at, INTERVAL #{hours_diff.abs} HOUR ))"
end
Foo.group(date_group).count

Related