Here you can find the source of getAge(Calendar dateOfBirth, Calendar onThisDay)
public static Integer getAge(Calendar dateOfBirth, Calendar onThisDay)
//package com.java2s; /**// w w w.j av a 2s . c o m * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main { /** * This method will calculate the age of the person on the given date. */ public static Integer getAge(Calendar dateOfBirth, Calendar onThisDay) { return (yearDifference(dateOfBirth, onThisDay)); } /** * date2-date1 * * if either are null, it returns null. */ public static Integer yearDifference(Date date1, Date date2) { if (date1 == null || date2 == null) return (null); Calendar cal1 = new GregorianCalendar(); cal1.setTime(date1); Calendar cal2 = new GregorianCalendar(); cal2.setTime(date2); return (yearDifference(cal1, cal2)); } /** * date2-date1 * * if either are null, it returns null. */ public static Integer yearDifference(Calendar date1, Calendar date2) { if (date1 == null || date2 == null) return (null); int yearDiff = date2.get(Calendar.YEAR) - date1.get(Calendar.YEAR); if (date2.get(Calendar.MONTH) > date1.get(Calendar.MONTH)) yearDiff--; else if (date2.get(Calendar.MONTH) == date1.get(Calendar.MONTH) && date2.get(Calendar.DAY_OF_MONTH) < date1.get(Calendar.DAY_OF_MONTH)) yearDiff--; return (yearDiff); } }