两个日期之间的Ruby差异

时间:2017-08-17 17:12:55

标签: ruby-on-rails date time

我需要检查两个日期之间的差异,并检查是否有24小时或更长时间。我在调用日期对象的to_time方法时遇到了麻烦。如果当前日期为00:00:00,则此to_time方法将分钟和秒数转换。

示例:

date = Date.rfc3339('2017-08-16T17:55:49.000-03:00')
=> #<Date: 2017-08-16 ((2457982j,0s,0n),+0s,2299161j)> 
date.to_time
2017-08-16 00:00:00 -0300 
(( Date.today.to_time - date.to_time)/3600).round
=> 24

2 个答案:

答案 0 :(得分:3)

Date不包含Time。请改用DateTime

require 'date'

dt = DateTime.rfc3339('2017-08-16T17:55:49.000-03:00')    
puts (Time.now - dt.to_time)/(60*60) > 24

答案 1 :(得分:1)

你可以这样做:

datetime_1 = DateTime.parse("2017-08-17T13:36:03-04:00")
datetime_2 = DateTime.parse("2017-08-16T13:33:03-04:00")
greatest_datetime = [datetime_1, datetime_2].max
smallest_datetime = [datetime_1, datetime_2].min
(greatest_datetime - 1.day) > smallest_datetime