Forum: Ruby on Rails RE: calculate age based on DoB

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.
Jonathan V. (Guest)
on 2005-12-19 01:26
(Received via mailing list)
What about this:

def age
  Time.now.year - date_of_birth.year - (
    ((date_of_birth.month * 31 + date_of_birth.day > Time.now.month * 31
+ Time.now.day) and Time.now.year != date_of_birth.year) ? 1 : 0
  ) unless date_of_birth.blank?
end

That should work I think.

-Jonathan.
Jeroen H. (Guest)
on 2005-12-19 11:10
(Received via mailing list)
Jonathan V. wrote:
> What about this:
>
> def age
>   Time.now.year - date_of_birth.year - (
>     ((date_of_birth.month * 31 + date_of_birth.day > Time.now.month * 31
> + Time.now.day) and Time.now.year != date_of_birth.year) ? 1 : 0
>   ) unless date_of_birth.blank?
> end
>
> That should work I think.

It seems people are now 1 year younger than they actually are. So one
could claim this is the best implementation yet.

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