Java Age Calculate calculateAge(Date aDateFrom, Date aDateTo)

Here you can find the source of calculateAge(Date aDateFrom, Date aDateTo)

Description

calculate Age

License

Open Source License

Parameter

Parameter Description
aDateFrom - Date to calculate age from
aDateTo - Date to calculate age to

Return

int - the age difference

Declaration


public static int calculateAge(Date aDateFrom, Date aDateTo) 

Method Source Code

//package com.java2s;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    /**// w w w.j  a  v a  2  s .c  o m
     *
     * @param aDateFrom - Date to calculate age from
     * @param aDateTo - Date to calculate age to
     * @return int - the age difference
     *
     */
    /*==============================================================*/
    public static int calculateAge(Date aDateFrom, Date aDateTo) {
        int result;
        // Prepare a Calendar object for querying values
        Calendar myDateFrom = new GregorianCalendar();
        Calendar myDateTo = new GregorianCalendar();
        myDateFrom.setTime(aDateFrom);
        myDateTo.setTime(aDateTo);
        // Determine rough number of years
        result = myDateTo.get(Calendar.YEAR) - myDateFrom.get(Calendar.YEAR);
        // If the from date has not occurred this year then subtract a year
        myDateFrom.set(Calendar.YEAR, myDateTo.get(Calendar.YEAR));
        if (myDateFrom.after(myDateTo)) {
            result--;
        }
        return result;
    }
}

Related

  1. age(Date dob)
  2. age(int year, int month, int date)
  3. ageAcceptable(final Date doB, final Date now, final int acceptedAge)
  4. ageInYears(java.util.Date dateUtil)
  5. calculateAge(Date aBirthdate)
  6. calculateAge(Date birthDate)
  7. calculateAge(Date birthday)
  8. calculateAge(Date dateOfBirth)
  9. calculateAge(Date dob)