在红宝石的两个日期之间没有几个月,几年

时间:2013-09-19 10:51:45

标签: ruby

我正在尝试编写web ui测试,根据用户输入(watir-webdriver)从jquery日历中选择日期,如何在两个给出日期之间找不到几个月,我搜索的几个解决方案无法得到我的想

date1 = Date::strptime("2013-09-19", "%Y-%m-%d")  
date2 = Date::strptime("2013-09-25", "%Y-%m-%d")  
date3 = Date::strptime("2013-10-01", "%Y-%m-%d")  
date4 = Date::strptime("2014-01-20", "%Y-%m-%d")  
date5 = Date::strptime("2014-12-01", "%Y-%m-%d")  

所需的输出

diff between date1,date2 -- 0 yrs, 0 month(s)  
diff between date1,date3 -- 0 yrs, 1 month(s)  
diff between date1,date4 -- 0 yrs, 4 month(s)  
diff between date1,date5 -- 1 yrs, 3 month(s)  

我检查了time_diff gem

3 个答案:

答案 0 :(得分:8)

我会计算月份差异(请注意我们忽略了这里的日差异),然后将该数字除以12来计算年数:

##
# Calculates the difference in years and month between two dates
# Returns an array [year, month]
def date_diff(date1,date2)
  month = (date2.year * 12 + date2.month) - (date1.year * 12 + date1.month)
  month.divmod(12)
end

date_diff date1, date4 #=> [0, 4]
date_diff date1, date2 #=> [0, 0]
date_diff date1, date3 #=> [0, 1]
date_diff date1, date5 #=> [1, 3]

答案 1 :(得分:3)

Here is my attempt. Works in multiple units:

  def date_diff(date1, date2, units=:months)
    seconds_between = (date2.to_i - date1.to_i).abs
    days_between = seconds_between / 60 / 60 / 24

    case units
      when :days
        days_between.floor
      when :months 
        (days_between / 30).floor
      when :years
        (days_between / 365).floor
      else
        seconds_between.floor
    end
  end

Usage:

date_diff(Time.now, 10.years.ago - 77.days, :years)  #=> 10 
date_diff(10.years.ago - 77.days, Time.now, :months) #=> 124
date_diff(10.years.ago - 77.days, Time.now, :days)   #=> 3730

答案 2 :(得分:0)

这是我从 TimeDifference gem 那里拿来的,但效果很好,我想我会分享的。如果您使用 Rails,请使用以下代码创建一个名为 TimeDifference 的类:

class TimeDifference
  private_class_method :new

  def self.between(start_time:, end_time:)
    new(start_time, end_time)
  end

  def in_seconds
    @time_diff
  end

  def in_minutes
    in_component(:minutes)
  end

  def in_hours
    in_component(:hours)
  end

  def in_days
    in_component(:days)
  end

  def in_weeks
    in_component(:weeks)
  end

  def in_months
    (@time_diff / (1.day * 30.42)).round(2)
  end

  def in_years
    in_component(:years)
  end

  private

  def initialize(start_time, end_time)
    start_time = time_in_seconds(start_time)
    end_time   = time_in_seconds(end_time)
    @time_diff = (end_time - start_time).abs
  end

  def time_in_seconds(time)
    time.to_time.to_f
  end

  def in_component(component)
    (@time_diff / 1.send(component)).round(2)
  end
end

然后只需调用:

start_time = DateTime.parse('2 June, 1999 9:00:00')
end_time = DateTime.parse('19 April, 2021 9:00:00')

time_difference = TimeDifference.between(
  start_time: start_time,
  end_time: end_time
)

time_difference.in_days
=> 7992.0

time_difference.in_months
=> 262.72

time_difference.in_years
=> 21.88

注意:如果您不使用 Rails,则可能需要使用 ActiveSupport。