Forums Register Login

Is there a better way to calculate age?

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Try this
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
Please read this...

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


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

Henry
+Pie Number of slices to send: Send
. . . 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.
Do not set lab on fire. Or this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 55742 times.
Similar Threads
how to caculate first day / last day of a week ?
Help with Date class
How to get current date and time
date question
Possble Calendar bug with daylight saving time
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 18, 2024 20:09:31.