用 Ruby 减去日期

发布于 2024-10-02 12:48:26 字数 497 浏览 0 评论 0原文

我只是看看 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 = (((age / 3600) / 24) / 365).to_i
=> 7

所以我的例子不太好,因为age_in_years不知道这些年份加起来是否有闰年。 我已经通过谷歌搜索了一些时间/日期教程,但没有找到一种简单的方法来减去两个日期并让它以年、月、日等格式返回。 我猜 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

救星 2024-10-09 12:48:26

您想要 日期< /a> 而不是 时间

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'

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

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

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

2010 - 2000 # => 10

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文