Rails query find result with partiular day with where cluase

52 views Asked by At

I want to orders which are confirmed particular day.

This is particular day:

today = Time.zone.now

Wed, 10 Jun 2015 13:31:16 IST +05:30

This is range of particular day

value = today.beginning_of_day()..today.end_of_day()
Wed, 10 Jun 2015 00:00:00 IST +05:30..Wed, 10 Jun 2015 23:59:59 IST +05:30

But when I execute this, SQL query date range is changed,

orders = Order.where(confirmed_at: value)

SELECT "orders".* FROM "orders" WHERE "orders"."confirmed_at" BETWEEN '2015-06-09 18:30:00.000000' AND '2015-06-10 18:29:59.999999' ORDER BY orders.confirmed_at DESC

In this orders confiremed between '2015-06-09 18:30:00.000000' AND '2015-06-10 18:29:59.999999'

But I wants confirmed between 'Wed, 10 Jun 2015 00:00:00 IST +05:30..Wed, 10 Jun 2015 23:59:59 IST +05:30'

2

There are 2 answers

0
Aakash Aggarwal On

You can use Time.zone.now.to_time for today.

today = Time.zone.now.to_time

value = today.beginning_of_day()..today.end_of_day()

I hope this helps.

1
tompave On

Which DB are you using?

ActiveRecord will declare time columns using data types that do not support timezones. For example, in Postgres it will use timestamp without time zone.

This means that all Time, DateTime and TimeWithZone values set on an ActiveRecord object will be written to the DB as UTC.
Rails will then take care to apply and remove the right offsets each time the values are read or written, using the current value of Time.zone (e.g. for the current web request).

Just check the docs for TimeWithZone and think about what should go in your WHERE clause. It probably depends on the specific context, but you might have to use UTC values in your query.