用 Ruby 减去日期
我只是看看 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要
日期
< /a> 而不是时间
:
将为您提供今天与 2000 年 1 月 1 日之间的年差。它可能可以改进,我只是使用每年的平均天数 (365.25),这将为您提供正确的答案,除了极端边缘情况。
你也可以这样做:
但是
Date#next_year
是在 Ruby 1.9 中引入的,所以它在 1.8.7 中不起作用。当然,确定两个日期之间的年数的最简单方法就是减去数字:
You want
Date
instead ofTime
: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:
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: