Reputation: 2159
I have Orders in my DB where created_at
is very important.
When a new order is created by a client and hence saved to the database, the created_at
is one hour ahead, e.g. if an order is created at 3:00 the created_at
in the DB will be 2:00.
I actually configured my application.rb
in order to solve the issue:
# timezone
config.time_zone = 'Paris'
config.active_record.default_timezone = :local
But when I make time comparison in my controller, it does work.
Order.where("created_at >= :start_time and meal_id = :meal", start_time: DateTime.new(Date.today.year, Date.today.month, Date.today.day - 1, 17, 0, 0), meal: @meal.ids[0])
The above code should display all orders that where created since yesterday 5:00pm, but the ones created from 5:00pm to 6:00pm are actually missing.
Again, the created_at
for each meal is the right one when I look at my table in Active Admin for example, but it one hour ahead when looking at it in the console.
How can I solve this ?
Upvotes: 0
Views: 482
Reputation: 2159
OK so after trying several things, there was actually two issues:
the first one was regarding Time, indeed. The second was @meal variable (I was using .where
to get the right meal, but using .find_by
made it work)
I added a "+01:00"
a the end of my DateTime Object and it did the trick:
Order.where("created_at >= :start_time and meal_id = :meal", start_time: DateTime.new(Date.today.year, Date.today.month, Date.today.day - 1, 17, 0, 0, "+01:00"), meal: @meal.id)
Upvotes: 0
Reputation: 8604
The time in database is UTC time, it's stored correctly. So you can compare with utc time to get expected result:
Order.where("created_at >= :start_time", start_time: 1.day.ago.beginning_of_day.utc + 16.hours)
so if database stores 16:00
in utc, it means 5pm in your timezone.
Upvotes: 1
Reputation: 8041
Try 1.day.ago
, which takes into account time zone, which your code does not.
Order.where("created_at >= :start_time and meal_id = :meal", start_time: 1.day.ago, meal: @meal.ids[0])
If you want the beginning of the hour specifically, as your code implies, try 1.day.ago.beginning_of_hour
:
Order.where("created_at >= :start_time and meal_id = :meal", start_time: 1.day.ago.beginning_of_hour, meal: @meal.ids[0])
Side note: With Rails, if you find yourself doing some kind of complex date manipulation, you should see if Rails already supports it. There are tons more functions here
Upvotes: 1