December 19, 2023

Time vs Date

When performing a query for a date column, it shouldn't come a much of a surprise that you would be in your best interest to pass a date as opposed to a timestamp. 

However, sometimes with complex reporting, you may collect a date from a user using a date picker and you may need to use that date to to query multiple columns across several tables. In some instances you may be searching a date column and in some a time column. If you're not searching for a specific time, you typically want to get the end_of_day to include all times from that day. 

But if you use this same date variable for a date column, it will have unintended results.

In the below example, I want to search for all tickets on or before 12/18/2023, but you can see when rails converts that to UTC, it pushed it into the 19th, and since we're searching a date column, Postgresql will typecast the timestamp as 12/19/2023 and my result will include tickets from the 19th. 

I almost wish there was an option to have rails throw an exception if you pass a timestamp to a date column. Or maybe that's a better job for rubocop some other linter??

At the end of the day, it's probably a good habit to call to_date on your date or time object.