0

Possible Duplicate:
How do I calculate someone's age in Java?

I'm creating an application in spring framework which calculates the age after a user enters their birthdate to a UI. So far my getAge bean has the gets and sets, but how do I right the calculation method syntatically?

import java.util.*;
public class ageBean {

Date birthdate;


public Date getBirthday(){
return birthdate;
}
 public void setBirthdate(Date birthdate){
this.birthdate=birthdate;
}

   //method goes here 
    }
Community
  • 1
  • 1
John Dunn
  • 1
  • 1
  • Check this: http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java – fmgp May 03 '12 at 16:31
  • 3
    see http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java. It doesn't look like you are using spring for anything, it is a framework that enabled IoC and other features. – stevebot May 03 '12 at 16:31

3 Answers3

0

There is nothing with Spring . if you want to calculate current age,

    long diff = new Date().getTime() - birthdate.getTime(); // current date - b'day
    long diffSeconds = diff / 1000;         
    long diffMinutes = diff / (60 * 1000);         
    long diffHours = diff / (60 * 60 * 1000);                      
    System.out.println("Time in seconds: " + diffSeconds + " seconds.");         
    System.out.println("Time in minutes: " + diffMinutes + " minutes.");         
    System.out.println("Time in hours: " + diffHours + " hours."); 
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

Use java.util.Calendar to ensure leap years, varying numbers of days in month etc. are accounted for,

int thisYear = Calendar.getInstance().get(Calendar.YEAR);
Calendar birthdateCalendar = Calendar.getInstance();
birthdateCalendar.setTime(birthdate);
int birthYear = birthdateCalendar.get(Calendar.YEAR);
int yearsSinceBirth = thisYear - birthYear;
cvanes
  • 31
  • 3
0

You can try this piece of code by replacing date1 with your birthdate,

Date date= new Date(System.currentTimeMillis());
date.setYear(date.getYear()+1900);

// this is done as currentTimeMillis returns the time elapsed from 1 Jan 1970s

Date date1=new Date(2000,10,15);
long timegap =date.getTime()-date1.getTime();
long milliSecsInAYear = 31536000000L;

System.out.println(timegap/milliSecsInAYear+"years" +((date.getTime()-date1.getTime())%milliSecsInAYear)/(milliSecsInAYear/365)+"days" );

note : I have taken a year as having 365 days

abson
  • 9,148
  • 17
  • 50
  • 69