Haseeb Ahmad
Haseeb Ahmad

Reputation: 8740

Check greater than of updated_at in where clause in ruby on rails

I get updated_at in params as a string. I convert it by using to_time

updated_at = params["latest_updated_at"].to_time
chat_history = ChatHistory.where('updated_at > ?',updated_at)

But it doesn't work properly. It also get a few < updated_at records. I want only > update_at.

Value of param is like "2016-03-17 18:06:36"

Upvotes: 1

Views: 1972

Answers (1)

Paul A Jungwirth
Paul A Jungwirth

Reputation: 24591

So this might be a timezone issue. If your timestamps are always expressed in the same timezone, you can say this:

ActiveSupport::TimeZone['America/Los_Angeles'].parse "2016-03-17 18:06:36"

That will give you a TimeWithZone instance, which you can pass to the where call. (Of course change America/Los_Angeles to whatever is appropriate.) A shortcut might be Time.zone.parse if you've configured Rails to use the timezone you want.

If the timezone can vary based on, say, current_user, just use the user's preferences to get the right timezone, then use that to parse your string.

Btw you are getting a lot of bad advice in the comments on your question:

  • You should not use to_date, because then you lose all sub-day resolution. If you don't account for timezones properly you might not even pick the right day!

  • Parsing the string then calling in_time_zone does nothing, because by parsing the string you've already interpreted it in one timezone or another. in_time_zone doesn't change what instant the time is, only where you're standing at that moment, and hence whether it should be written as "5pm Pacific" or "6pm Central".

Here is some general advice on timezones in Rails, and how to reason about them (by me): http://illuminatedcomputing.com/posts/2014/04/timezones/

Upvotes: 2

Related Questions