Here you can find the source of calculateAge(Date aDateFrom, Date aDateTo)
Parameter | Description |
---|---|
aDateFrom | - Date to calculate age from |
aDateTo | - Date to calculate age to |
public static int calculateAge(Date aDateFrom, Date aDateTo)
//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; } }