3

我正在尝试编写 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

4

3 回答 3

10

我会计算月差(请注意,我们在这里忽略了日差),然后通过将该数字除以 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]
于 2013-09-19T11:23:53.620 回答
3

这是我的尝试。在多个单位工作:

  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

用法:

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
于 2016-07-11T21:55:44.457 回答
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。

于 2021-04-19T05:41:10.367 回答