Recently I encountered a problem in my Rails application.
I was working on time comparison for an event based system.
So, What I wanted was, to do escalation matrix for certain events, those events are time based events hence I needed to do time comparison.
Ruby has Time and DateTime module which are there for time/date calculations.
Time module is older module it will calculate time since January 1, 1970 UTC.
On the other hand the DateTime has much wider scope, it does not limit itself for specific date/time range.
Time and DateTime are pretty similar and confusing at the same time.
You can read more about this here
So coming to the problem, in my system I have a created_at for the object and event_time for the event time(at what time the event occurred).
I have stored everything in UTC.
to_time
>> DateTime.parse("04/10/2019 12:04 PM").utc.to_time
# => 2019–10–04 17:34:00 +0530
to_datetime
>> DateTime.parse("04/10/2019 12:04 PM").utc.to_datetime
# => Fri, 04 Oct 2019 12:04:00 +0000
So you see the difference, to_time gives time in your time_zone, Mumbai in my case. But to_datetime gives the time in UTC time.
to_time returns Time object and to_datetime returns the DateTime object hence the outputs are different.
So when to use to_time and to_datetime?
In my case, my mistake was I was parsing the DateTime object to to_time which was not a good idea. And then I changed to to_datetime which solved my problem.
If you know you are using DateTime you should use to_datetime if needed and if you are using Time you should use to_time format. This will solve most of the issues.
Common mistakes I have seen people do is they create a Time object and then parse it using to_datetime, create a DateTime object and parse it using to_time. This might not cause any problems in many systems knowing what is the return value.