2017-08-17 243 views
0

我需要檢查兩個日期之間的差異並檢查是否有24小時或更長時間。我在調用日期對象的to_time方法時遇到問題。如果當前日期爲00:00:00,則此to_time方法正在將分鐘和秒數轉向。兩個日期之間的Ruby差異

實施例:

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 

回答

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

你可以這樣做:

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