Subtracting dates with Ruby

不想你离开。 提交于 2019-12-29 06:37:07

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/4177102/subtracting-dates-with-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!