Search code examples
ruby-on-rails-4rails-activerecorddelayed-jobsidekiqresque

Which DateTime method to use to fetch records for particular day?


I have a background worker in my web app that must fetch and process all records for given day.

For example if I specify Nov 30 2015 it should fetch records from Nov 30 2015 00:00:00 to Nov 30 2015 23:59:59.

Previously I was using DateTime.now and it appears to work fine, but today I noticed in rails console that ActiveRecord generates SQL with wrong (from my app logic' point of view) dates range: from Nov 29 2015 22:00:00 to Nov 30 2015 21:59:59.

I am afraid that DateTime.now might fetch wrong records or will not fetch required ones.

DateTime.current on the other hand seems to generate correct dates ranges (from 00:00AM to 23:59PM). Should I use it instead of DateTime.now?

DateTime.now:

date_to_check = DateTime.now
# Mon, 30 Nov 2015 12:33:36 +0200

DailyDiagramsLog.where(
    day: date_to_check.beginning_of_day..date_to_check.end_of_day)

# SELECT "daily_diagrams_logs".* FROM "daily_diagrams_logs" 
# WHERE ("daily_diagrams_logs"."day" 
# BETWEEN '2015-11-29 22:00:00.000000' AND '2015-11-30 21:59:59.000000')

DateTime.current:

date_to_check = DateTime.current
# Mon, 30 Nov 2015 10:35:27 +0000

DailyDiagramsLog.where(
    day: date_to_check.beginning_of_day..date_to_check.end_of_day)

# SELECT "daily_diagrams_logs".* FROM "daily_diagrams_logs" 
# WHERE ("daily_diagrams_logs"."day" 
# BETWEEN '2015-11-30 00:00:00.000000' AND '2015-11-30 23:59:59.000000')

Solution

  • You can use Date.today for getting records for a specific day like:-

    date = Date.today
    DailyDiagramsLog.where(:day => (date.beginning_of_day..date.end_of_day))
    or
    time = Time.now
    DailyDiagramsLog.where(:day => time.beginning_of_day..time.end_of_day)