Ruby 将日期戳转换为 Ruby 中的年份

发布于 2024-11-06 18:03:12 字数 280 浏览 4 评论 0原文

可能的重复:
如何计算多少年从 Ruby 中的给定日期开始已经过去了?

我正在尝试将从数据库中获取的日期戳转换为指示一个人有多少岁的值。我确信这很容易,但我似乎无法弄清楚。

Possible Duplicate:
How to calculate how many years passed since a given date in Ruby?

I am trying to convert a datestamp taken from the database into value indicating how many years old a person is. I am sure this easy, but I can't seem to figure it out.

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

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

发布评论

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

评论(1

一抹苦笑 2024-11-13 18:03:12

假设将日期戳作为日期时间值检索:

require 'date'

birth_date = DateTime.parse('1970-01-01 1:35 AM')
time_now = DateTime.now

(time_now - birth_date).to_i / 365 # => 41
(time_now - birth_date).to_f / 365 # => 41.38907504054664

birth_date 是您应该从数据库中检索的模拟值。第一个值是年,第二个值是小数年。

或者,您可以这样做:

years = time_now.year - birth_date.year
years -= 1 if (birth_date.month > time_now.month)
years # => 41

如果此人尚未过生日,则会进行调整。例如,调整生日:

birth_date = DateTime.parse('1970-12-31 11:59 PM')
years = time_now.year - birth_date.year
years -= 1 if (birth_date.month > time_now.month)
years # => 40

Assuming the datestamp is being retrieved as a DateTime value:

require 'date'

birth_date = DateTime.parse('1970-01-01 1:35 AM')
time_now = DateTime.now

(time_now - birth_date).to_i / 365 # => 41
(time_now - birth_date).to_f / 365 # => 41.38907504054664

birth_date is a mock value for what you should be retrieving from your database. The first value is years, the second is fractional years.

Alternately, you can do it this way:

years = time_now.year - birth_date.year
years -= 1 if (birth_date.month > time_now.month)
years # => 41

This adjusts in case the person hasn't had their birthday yet. For instance, tweaking the birthday:

birth_date = DateTime.parse('1970-12-31 11:59 PM')
years = time_now.year - birth_date.year
years -= 1 if (birth_date.month > time_now.month)
years # => 40
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文