I'd like to get a person's age from its birthday. now - birthday / 365
doesn't work, because some years have 366 days. I came up with the following code:
now = Date.today
year = now.year - birth_date.year
if (date+year.year) > now
year = year - 1
end
Is there a more Ruby'ish way to calculate age?
I like this one:
DateHelper can be used to get years only
My suggestion:
The trick is that the minus operation with Time returns seconds
I know I'm late to the party here, but the accepted answer will break horribly when trying to work out the age of someone born on the 29th February on a leap year. This is because the call to
birthday.to_date.change(:year => now.year)
creates an invalid date.I used the following code (in a Rails project) instead:
I had to deal with this too, but for months. Became way too complicated. The simplest way I could think of was:
You could do the same with 12 months:
This will use Date class to increment the month, which will deal with 28 days and leap year etc.