如何在days,hours,mins
我正在尝试
datetime_A - datetime_B
datetime_A
=星期六,2014年1月4日07:00:13 +0000
datetime_B
=星期五,2014年1月3日01:09:46 +0000
它返回了类似(35809/28800)
的内容,bdw是什么意思?
我需要1day,5h,23min
怎么办?
答案 0 :(得分:13)
您需要在rails应用中添加帮助才能实现此目的。 Ruby没有为此提供任何直接的方法。下面是使用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
答案 1 :(得分:5)
我喜欢使用gem time_diff
https://github.com/abhidsm/time_diff
这是一个如何运作的例子
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'}
答案 2 :(得分:5)
另一种方法是使用ActionView
助手distance_of_time_in_words
(请参阅documentation)。如果通常不给出确切的次要单位,但是大约5天左右就会出现#34;
答案 3 :(得分:2)
给出的值是Rational,(http://www.ruby-doc.org/core-2.1.5/Rational.html)。它表示两个日期之间的天数。这实际上非常酷,因为它可以比浮子更准确,并且可以轻松转换为小时,分钟,秒等。