# Is there a better way to calculate age?

Jamie Robertson
Ranch Hand
Posts: 1879
requirements: input into method are 3 Strings representing the person's birth year, month and day ( YYYY, MM, DD ). Returns the person's age as an integer.
current method:

it seems a little clunky to me. Someone out there must have a cleaner way.
Thanx,
Jamie

SoonAnn Lim
Ranch Hand
Posts: 155
You may convert the birthday in second unit(note that before 1970 is negative value). Then get the current time using System.getCurrentTimeMillis() and change it to second by dividing 1000. Define number of second in a year which is 365*24*60*60. Then age should be (current_time-birthday)/second_year. Just a thought.

Irene Loos
Ranch Hand
Posts: 78
Try this

Greenhorn
Posts: 1
Correct, excellent, neat solution except that:-
Calendar dob = Calendar.getInstance();
dob.setTime(dateOfBirth);
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
age--;
return age;

should be
Calendar dob = Calendar.getInstance();
dob.setTime(dateOfBirth);
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) <= dob.get(Calendar.DAY_OF_YEAR))
age--;
return age;

Noting <= .

Try testing both versions for a birthday with tomorrow's date and you will see what I mean.
[ September 23, 2008: Message edited by: Ade Gray ]

Henry Wong
author
Marshal
Posts: 21489
84

http://faq.javaranch.com/java/DontWakeTheZombies

Adding to a topic that is over 6 years old isn't very productive.

Henry

Campbell Ritchie
Sheriff
Posts: 50168
79
. . . but welcome to JavaRanch anyway

By the way, I think < was correct, not <=. There will be problems in leap years; 29th February 2008 returns the same DAY_OF_YEAR as 1st March 2007.