Francisco Francisco - 1 year ago 41
Ruby Question

rails How to calculate time difference with integer between 3 dates

How to compare 3 dates, ( - @model.updated_at) < :integer(converted to days) , So first is a substraction between two dates and the difference between the two dates as (amount of time) is compared(< less than) to an :integer.days(amount of time). Hope this makes sense... im going through different options but im just getting more confused. Thanks for any help.

"#{}".to_i.days - "#{:updated_at}".to_i.days < "#{:integer}".to_i.days

Answer Source

I have also faced the same scenario in one of my projects and there i used the Time Difference Gem . It is very simple and easy to integrate and provides you additional helper methods to get the difference in year, month, week, day, hour, minute, and seconds.

Set the start and end date

start_time =,1)
end_time =,1)

Now call the calculate the difference as

TimeDifference.between(start_time, end_time).in_days
=> 365.0

Additionally it provides you liberty to fetch all differences at the same time

TimeDifference.between(start_time, end_time).in_each_component
=> {:years=>1.0, :months=>12.0, :weeks=>52.14, :days=>365.0, :hours=>8760.0, :minutes=>525600.0, :seconds=>31536000.0}