Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is there a better way to calculate age?

 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this
 
Ade Gray
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20880
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please read this...

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: 48363
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic