Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting dates with Ruby

I'm just having a look at ruby and was playing with the date/time thing.

irb(main):001:0> jamis_DOB = Time.mktime(2003, 10, 22, 06, 59)
=> Wed Oct 22 06:59:00 +0300 2003
irb(main):002:0> age = Time.now - jamis_DOB
=> 222934108.172989
irb(main):005:0> age_in_years = (((age / 3600) / 24) / 365).to_i
=> 7

So my example is not so good as age_in_years won't know if there are leap years as those years add up. I've been through some googled time/date tutorials and haven't found an easy way to just subtract two dates and have it return in a years, months, days etc... format. I'm guessing ruby has an add-on or something built-in for this kind of thing. Could someone tell me what it is? (Also, any advice how to find the answers to this type of thing for future reference?)

Thanks.

like image 392
Leke Avatar asked Nov 14 '10 10:11

Leke


1 Answers

You want Date instead of Time:

require 'date'

now = Date.today
before = Date.civil(2000, 1, 1)
difference_in_days = (now - before).to_i

(difference_in_days/365.25).to_i

Will give you the difference in years between today and January 1st 2000. It can probably be improved, I just used the average number of days per year (365.25), which will give you the right answer except in extreme edge cases.

You can also do something like this:

require 'date'

years = 0
d = Date.civil(2000, 1, 1)
loop do
  d = d.next_year
  break if Date.today < d
  years += 1
end

But Date#next_year was introduced in Ruby 1.9, so it wouldn't work in 1.8.7.

Of course, the easiest way of determining the number of years between two dates is just subtracting the numbers:

2010 - 2000 # => 10
like image 123
Theo Avatar answered Sep 20 '22 18:09

Theo