Calculate users age

On 1/24/06, Paul B. [email protected] wrote:

This shows the errors in age_at better:

Thanks for pointing this out! I can’t imagine why I did not think of
this.

I am not in any way an endorser of trying to make code as short as
possible but out of curiosity I fixed my one-line class so that it now
correct but “unreadable”:

def age_at(date, dob)
date.year - dob.year - (date.month-dob.month < 0 ? 1 :
date.day-dob.day < 0 ? 1:0)
end


Jonas
Elfström

Here is a little bit i just put together.
I’ve not made it pretty and have only done some basic testing.

Context: this function is in a model which has a Date field called dob
it returns the age in “y years m months d days old” format skipping
values that are empty and pluralizing year month and day as appropriate.

ex: (Time.now = 2006/01/28)
dob [time_ago_in_words] [object.age_in_words]
2004-02-21 (age = 707 days) (1 year 11 months 7 days old)
2002-01-28 (age = 1461 days) (4 years old)
2005-08-20 (age = 161 days) (5 months 8 days old)

===========================
def age_in_words
if dob == nil
“–”
else
now = Time.now
ydiff = now.year - dob.year
mdiff = now.month - dob.month
ddiff = now.day - dob.day
if ((mdiff < 0) && (ydiff > 0))
y = ydiff - 1
m = mdiff + 12
else
y = ydiff
m = mdiff
end
if ((ddiff < 0) && (mdiff != 0))
m = m - 1
dim = Time.days_in_month(dob.month+m,dob.year+y)
d = (dim - dob.day) + now.day
else
d = ddiff
end

	end
	ys = "year"
	ms = "month"
	ds = "day"
	if (y.abs > 1)
		ys= ys.pluralize
	end
	if (m.abs > 1)
		ms = ms.pluralize
	end
	if (d.abs > 1)
		ds = ds.pluralize
	end
	year_string = (y !=  0)?"#{y} #{ys} ":""
	month_string = (m != 0)?"#{m} #{ms} ":""
	day_string = (d != 0)?"#{d} #{ds}":""
	return "#{year_string}#{month_string}#{day_string} old"
end

Am Montag, den 23.01.2006, 17:05 +0100 schrieb Norman T.:

I made a small enhancement for the Date class from it:

class date
def age(today = self.class.today)
today.year - year - ((today.month * 100 + today.day >= month * 100 +
day) ? 0 : 1)
end
end

I cleaned it a up a bit and made it more readable:

class Date
def age(base = self.class.today)
base.year - year - ((base.month * 100 + base.day >= month * 100 +
day) ? 0 : 1)
end
end

Use it like that:

to get the age for today

Date.new(1978,4,20).age

to get the age for January, the 1st, 2020

Date.new(1978,4,20).age(Date.new(2020,1,1))

You can validate the age of a person in this simple way:

class Person < ActiveRecord::Base
validates_inclusion_of :age, :in=>18…99

def age
# expecting that you have an attribute ‘date_of_birth’
# filled with a Date object
date_of_birth.age
end
end

Norman T.

http://blog.inlet-media.de