Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 396
Francisco Avatar asked Jul 27 '16 14:07

Francisco


People also ask

How does rails calculate time difference?

start_time: 22:00 (Rails interprets this as 2015-12-31 22:00:00 +0100) second_time: 02:00 (Rails interprets this as 2015-12-31 02:00:00 +0100). The second time is 4 hours later, so in the next day.

How do you find the time interval between two dates?

To calculate the time between two dates and times, you can simply subtract one from the other.

How do I get the current date in Ruby?

You can get the current date using Date. today .


2 Answers

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}
like image 84
Fakhir Shad Avatar answered Nov 15 '22 04:11

Fakhir Shad


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
like image 42
Simone Carletti Avatar answered Nov 15 '22 05:11

Simone Carletti