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?
This is a conversion of this answer (it's received a lot of votes):
It's definitely unique in its approach but makes perfect sense when you realise what it does:
The following seems to work (but I'd appreciate it if it was checked).
Came up with a Rails variation of this solution
Here's my solution which also allows calculating the age at a specific date:
Ok what about this:
This is assuming we are using rails, calling the
age
method on a model, and the model has a date database columndob
. This is different from other answers because this method uses strings to determine if we are before this year's birthday.For example, if
dob
is 2004/2/28 andtoday
is 2014/2/28,age
will be2014 - 2004
or10
. The floats will be0228
and0229
.b4bday
will be"0228" < "0229"
ortrue
. Finally, we will subtract1
fromage
and get9
.This would be the normal way to compare the two times.
This works the same, but the
b4bday
line is too long. The2016
year is also unnecessary. The string comparison at the beginning was the result.You can also do this
If you aren't using rails, try this
If you don't care about a day or two, this would be shorter and pretty self-explanitory.