【问题标题】:Ruby Converting Datestamp to Years old in Ruby [duplicate]Ruby在Ruby中将时间戳转换为岁[重复]
【发布时间】:2011-08-24 13:57:22
【问题描述】:

可能重复:
How to calculate how many years passed since a given date in Ruby?

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

【问题讨论】:

  • 总是有助于添加一些显示您尝试过的源代码。

标签: ruby datestamp


【解决方案1】:

假设日期戳作为 DateTime 值被检索:

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

【讨论】:

  • 它不会受到闰年的困扰。这只是一个快速而肮脏的价值。
猜你喜欢
  • 2012-05-07
  • 2011-05-02
  • 2010-12-20
  • 2016-08-23
  • 2015-08-09
  • 2015-03-01
  • 1970-01-01
  • 2011-04-18
  • 2011-04-16
相关资源
最近更新 更多