Francisco
Francisco

Reputation: 183

rails How to calculate time difference with integer between 3 dates

How to compare 3 dates, (Time.now - @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.

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

Upvotes: 5

Views: 2873

Answers (3)

souravlahoti
souravlahoti

Reputation: 736

I like to use the gem time_diff

You can use

github

Here is a example how it works

Time.diff(Time.parse('2011-03-06'), Time.parse('2011-03-07'))
# => {:year => 0, :month => 0, :week => 0, :day => 1, :hour => 0, :minute => 0, :second => 0, :diff => '1 day and 00:00:00'}

the difference can match with the third_date

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176422

If you are using Rails, you can get the difference in seconds between two time objects using

time1 - time2

For example:

diff = 3.days.ago - Time.current
# -259200.000132

Use to_i to get the integer difference.

diff.to_i
-259200

The value is in seconds. Hence to get the days simply use:

((5.days.ago - 1.day.ago).to_i / 86400).abs
# => 4

Upvotes: 4

Fakhir Shad
Fakhir Shad

Reputation: 1101

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 = Time.new(2013,1)
end_time = Time.new(2014,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}

Upvotes: 4

Related Questions