2011-05-13 17 views

回答

2

假設郵戳被檢索的日期時間值:

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 
+0

它不會爲閏年而煩惱。這只是一個快速和骯髒的價值。 – 2011-05-13 02:52:52