Rails get the difference between two dates

How to get the time difference in days,hours,mins

I'm trying to do

datetime_A - datetime_B

datetime_A= Sat, Jan 04 2014 07:00:13 +0000

datetime_B= Fri, Jan 03 2014 01:09:46 +0000

he returns me something like (35809/28800), bdw, what does this mean?

I need both 1day,5h,23min

How to do it?

+4
source share
4 answers

You need to add a helper to your rails application to achieve this. Ruby does not provide a direct path for this. Below is the date processing using ruby ​​2.1.0.

2.1.0 :021 > a_date_time = DateTime.now
 => Fri, 26 Dec 2014 16:39:30 +0530 # First Date
2.1.0 :022 > b_date_time = DateTime.now-20
 => Sat, 06 Dec 2014 16:40:03 +0530 # Second Date
2.1.0 :023 > (a_date_time - b_date_time).to_i
 => 19 # Direct date difference
2.1.0 :024 > Seconds = ((a_date_time - b_date_time)*24*60*60).to_i
 => 1727966 # Seconds between two dates
2.1.0 :025 > sec = Seconds % 60
 => 26 # Second diffence to print
2.1.0 :026 > Minutes = Seconds / 60
 => 28799 # Minutes between two dates
2.1.0 :027 > min = Minutes % 60
 => 59 # Minute diffence to print
2.1.0 :028 > Hours = Minutes / 60
 => 479 # Hours between two dates
2.1.0 :029 > hour = Hours % 24
 => 23 #Hour diffence to print
2.1.0 :030 > Days = Hours / 24
 => 19 # Days between two dates
2.1.0 :032 > Days.to_s + 'Days, ' + hour.to_s + 'Hours, '+ min.to_s + 'Mins, ' + sec.to_s + 'Secs'
 => "19Days, 23Hours, 59Mins, 26Secs" # Desired output
+11
source

I like to use a gem time_diff

https://github.com/abhidsm/time_diff

Here is an example of 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'}
+5
source

ActionView distance_of_time_in_words (. ). , - " 5 ".

+5
source

The value that is given is Rational, ( http://www.ruby-doc.org/core-2.1.5/Rational.html ). It represents the number of days between two dates. This is actually pretty cool as it can be much more accurate than a float and can easily be converted to hours, minutes, seconds, etc.

+2
source

Source: https://habr.com/ru/post/1569036/


All Articles