用Ruby减去日期 [英] Subtracting dates with Ruby

查看:128
本文介绍了用Ruby减去日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是看看红宝石,正在玩日期/时间的事情。

  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 =(((年龄/ 3600)/ 24)/ 365).to_i
=> 7

所以我的例子不是很好,因为age_in_years不知道是否有闰年几年加起来
我已经通过一些谷歌的时间/日期教程,没有找到一个简单的方法来减去两个日期,并在几年,几个月,几天等格式返回。
我猜红宝石有一个附加组件或内置的这种东西。有人可以告诉我这是什么吗? (另外,任何建议如何找到这种类型的东西的答案以备将来参考?)



谢谢。

解决方案

你想要 日期 ,而不是 时间

 code> 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

会给你差别在2000年1月1日之间的几年里,可能会有所改善,我刚刚使用了每年的平均天数(365.25),除了极端的情况,这将给你正确的答案。



你也可以这样做:

  require'date'

年= 0
d = Date.civil(2000,1,1)
loop do
d = d.next_year
如果Date.today< d
年+ = 1
结束

Date#next_year 在Ruby 1.9中引入,所以在1.8.7中不起作用。



当然,最简单的确定方法两个日期之间的年数只是减去数字:

  2010  -  2000#=> 10 


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.

解决方案

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

这篇关于用Ruby减去日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆