Forum: Ruby on Rails Age calculation

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
james (Guest)
on 2005-11-25 13:32
(Received via mailing list)
Has anyone written some code to calculate a persons age based on their
date of birth?
Daniel -. (Guest)
on 2005-11-25 15:57
(Received via mailing list)
Hi James

I've been using this in my model.  The field in the database is called
"birthday" creative I know ;)

def age
      the_date = Time.now
      if the_date.month < birthday.month or
              (the_date.month == birthday.month and the_date.day <
birthday.day )
          the_date.year - birthday.year - 1
      else
          the_date.year - birthday.year
      end
  end

If anyone can see any issues with this please let me know.

thanx
hammed (Guest)
on 2005-11-25 20:16
(Received via mailing list)
((Date.today - birthday).to_i)/365 will give you the age in years.

Hammed
Daniel -. (Guest)
on 2005-11-26 01:27
(Received via mailing list)
On 11/26/05, Hammed M. <removed_email_address@domain.invalid> wrote:
>
> ((Date.today - birthday).to_i)/365 will give you the age in years.


Much Nicer.  Thanx

Hammed
rob (Guest)
on 2005-11-27 05:07
(Received via mailing list)
On Nov 25, 2005, at 3:31 AM, James Geary wrote:
> Has anyone written some code to calculate a persons age based on
> their date of birth?

Assuming #date_of_birth returns a Date object (or nil):

   def age
     dob = date_of_birth or return nil
     now = Time.now
     now.year - dob.year -
       (dob.to_time.change(:year => now.year) > now ? 1 : 0)
   end

--
Rob L.
removed_email_address@domain.invalid
emmett.shear (Guest)
on 2005-11-27 06:52
(Received via mailing list)
Warning: You're going to get one off errors because of leap years.

Emmett
This topic is locked and can not be replied to.