The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples] > Dates  [7 examples]

e377. Determining a Person's Age

This example uses the Calendar class to compute a person's age.
    // Create a calendar object with the date of birth
    Calendar dateOfBirth = new GregorianCalendar(1972, Calendar.JANUARY, 27);
    
    // Create a calendar object with today's date
    Calendar today = Calendar.getInstance();
    
    // Get age based on year
    int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);
    
    // Add the tentative age to the date of birth to get this year's birthday
    dateOfBirth.add(Calendar.YEAR, age);
    
    // If this year's birthday has not happened yet, subtract one from age
    if (today.before(dateOfBirth)) {
        age--;
    }

 Related Examples
e373. Getting the Current Date
e374. Creating a Date Object for a Particular Date
e375. Determining the Number of Days in a Month
e376. Comparing Dates
e378. Determining If a Year Is a Leap Year
e379. Determining the Day-of-Week for a Particular Date

See also: Arrays    Bits    Collections    Hash Tables    Lists    Property Files    Sets    Sorted Collections    Time    Timers   


© 2002 Addison-Wesley.