StaleElementException StaleElementException - 4 months ago 24
Ruby Question

get no of months, years between two dates in ruby

I'm trying to write web ui tests to choose date from jquery calender based on user input (watir-webdriver), how can find no of months years between two give dates, i searched few solution couldn't get what i want

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")


desired output

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)


i checked time_diff gem also

Answer

I'd calculate the difference in months (be aware that we ignore day differences here) and then calculate the number of years by dividing that number by 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]
Comments