Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get no of months, years between two dates in ruby

Tags:

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

like image 961
StaleElementException Avatar asked Dec 15 '25 12:12

StaleElementException


1 Answers

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]
like image 128
tessi Avatar answered Dec 18 '25 08:12

tessi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!