|
|
Question : age calculation
|
|
Hi experts,
I am trying to calculate age in rails.
I did something like this, but I know I am not considering leap years/months. +++++++++++ class AttendingIp < ActiveRecord::Base def age age = Date.today.year - read_attribute(:dob).year if Date.today.month < read_attribute(:dob).month || (Date.today.month == read_attribute(:dob).month && read_attribute(:dob).day >= Date.today.day) age = age - 1 end month = Date.today.month - read_attribute(:dob).month if(Date.today.month < read_attribute(:dob).month) month = 12 - read_attribute(:dob).month end day = Date.today.day - read_attribute(:dob).day if(Date.today.day < read_attribute(:dob).day) day = 31 - read_attribute(:dob).day end
++++++ I went through ruby api, but didn't find solution. Is there nice way to do this in RoR?
thanks in advance
|
Answer : age calculation
|
|
here is the code, that should already be a lot faster
y_dif = now.year - born.year if Date.new(now.year - y_dif, now.month, now.day) < born y_dif = y_dif - 1 end
m_tot = 0 almost_close_date = Date.new(born.year + y_dif, born.month, born.day) while almost_close_date < now m_tot = m_tot + 1 almost_close_date = almost_close_date>>(1) end m_dif = m_tot - 1
close_date = born >>(m_dif + 12 * y_dif) d_dif = 0 while close_date < now d_dif = d_dif + 1 close_date = close_date+(1) end
puts y_dif, m_dif, d_dif
If this is still too slow, you could make the day count recursive and split day differences in two (such as in bubble sort :-)
but before you go down that route, check pl/sql first using the ruby code is less database dependent of course
cheers
Geert
|
|
|
|
|