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.
7a7674ea7cb9a6de3140d8a69d9929cc?d=identicon&s=25 james (Guest)
on 2005-11-25 12:32
(Received via mailing list)
Has anyone written some code to calculate a persons age based on their
date of birth?
9d1f5d2d9de70bd9a934f557dc95a406?d=identicon&s=25 Daniel ----- (liquid)
on 2005-11-25 14: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
0bcc972918891ef358b0b3dfb4e7f18b?d=identicon&s=25 hammed (Guest)
on 2005-11-25 19:16
(Received via mailing list)
((Date.today - birthday).to_i)/365 will give you the age in years.

Hammed
9d1f5d2d9de70bd9a934f557dc95a406?d=identicon&s=25 Daniel ----- (liquid)
on 2005-11-26 00:27
(Received via mailing list)
On 11/26/05, Hammed Malik <hammed@gmail.com> wrote:
>
> ((Date.today - birthday).to_i)/365 will give you the age in years.


Much Nicer.  Thanx

Hammed
114892d0cdbc61d4e686dac70495a22b?d=identicon&s=25 rob (Guest)
on 2005-11-27 04: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 Leslie
rob@mars.org
1471570c98865252c76fd8db961c0d4d?d=identicon&s=25 emmett.shear (Guest)
on 2005-11-27 05: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.