我正在尝试将从数据库中获取的日期戳转换为指示一个人的年龄的值。我确信这很容易,但我似乎无法弄清楚。
问问题
151 次
1 回答
2
假设日期戳作为 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
于 2011-05-13T01:54:48.857 回答