Here you can find the source of calculationAge(Date birthday, Date calculateDay)
public static final int calculationAge(Date birthday, Date calculateDay)
//package com.java2s; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main { public static final int calculationAge(Date birthday, Date calculateDay) { @SuppressWarnings("unused") int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays; Calendar calculate = Calendar.getInstance(); calculate.setTime(calculateDay); Calendar birth = Calendar.getInstance(); birth.setTime(birthday);// w w w .j av a2s .co m try { year = birth.get(Calendar.YEAR); if (year > calculate.get(Calendar.YEAR)) { System.out.println("Invalid year"); } month = birth.get(Calendar.MONTH); if (month < 0 || month > 11) { System.out.println("month between 1 to 12."); return 0; } else { // month--; if (year == calculate.get(Calendar.YEAR)) { if (month > calculate.get(Calendar.MONTH)) { System.out.println("Invalid month"); return 0; } } } day = birth.get(Calendar.DATE); if (month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || month == 9 || month == 11) { if (day > 31 || day < 1) { System.out.println("day between 1 to 31"); return 0; } } else if (month == 3 || month == 5 || month == 8 || month == 10) { if (day > 30 || day < 1) { System.out.println("day between 1 to 30"); return 0; } } else { if (new GregorianCalendar().isLeapYear(year)) { if (day < 1 || day > 29) { System.out.println("day between 1 to 29"); return 0; } } else if (day < 1 || day > 28) { System.out.println("day between 1 to 28."); return 0; } } if (year == calculate.get(Calendar.YEAR)) { if (month == calculate.get(Calendar.MONTH)) { if (day > calculate.get(Calendar.DAY_OF_MONTH)) { System.out.println("Invalid date"); return 0; } } } } catch (NumberFormatException ne) { System.out.println(ne.getMessage() + " is not a legal entry"); return 0; } Calendar bd = new GregorianCalendar(year, month, day); ageYears = calculate.get(Calendar.YEAR) - bd.get(Calendar.YEAR); if (calculate.before(new GregorianCalendar(calculate.get(Calendar.YEAR), month, day))) { ageYears--; ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH)); if (day > calculate.get(Calendar.DAY_OF_MONTH)) { ageDays = day - calculate.get(Calendar.DAY_OF_MONTH); } else if (day < calculate.get(Calendar.DAY_OF_MONTH)) { ageDays = calculate.get(Calendar.DAY_OF_MONTH) - day; } else { ageDays = 0; } } else if (calculate.after(new GregorianCalendar(calculate.get(Calendar.YEAR), month, day))) { ageMonths = (calculate.get(Calendar.MONTH) - (bd.get(Calendar.MONTH))); if (day > calculate.get(Calendar.DAY_OF_MONTH)) ageDays = day - calculate.get(Calendar.DAY_OF_MONTH) - day; else if (day < calculate.get(Calendar.DAY_OF_MONTH)) { ageDays = calculate.get(Calendar.DAY_OF_MONTH) - day; } else ageDays = 0; } else { ageYears = calculate.get(Calendar.YEAR) - bd.get(Calendar.YEAR); ageMonths = 0; ageDays = 0; } return ageYears; } }