aspose file tools*
The moose likes Beginning Java and the fly likes Is there a better way to calculate age? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Is there a better way to calculate age?" Watch "Is there a better way to calculate age?" New topic
Author

Is there a better way to calculate age?

Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
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

Joined: Jun 21, 2001
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

Joined: Apr 15, 2002
Posts: 78
Try this


Irene Loos
Ade Gray
Greenhorn

Joined: Sep 23, 2008
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
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Please read this...

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


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

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39416
    
  28
. . . 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Is there a better way to calculate age?