Here you can find the source of calculateAgeInMonth(final Date birthDate, final Date asOfDate)
Parameter | Description |
---|---|
birthDate | the birth date |
asOfDate | the reference date to calculate the age |
private static int calculateAgeInMonth(final Date birthDate, final Date asOfDate)
//package com.java2s; /**//from w w w . j a va 2s.co m * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main { /** * Calculate age based on the birth date and the reference date. The returned age is in month. The remaining days will be rounded to the closest one * month value. * * @param birthDate the birth date * @param asOfDate the reference date to calculate the age * @return the age in month */ private static int calculateAgeInMonth(final Date birthDate, final Date asOfDate) { Calendar birthCalendar = Calendar.getInstance(); birthCalendar.setTime(birthDate); Calendar todayCalendar = Calendar.getInstance(); todayCalendar.setTime(asOfDate); int birthYear = birthCalendar.get(Calendar.YEAR); int todayYear = todayCalendar.get(Calendar.YEAR); int ageInYear = todayYear - birthYear; int birthMonth = birthCalendar.get(Calendar.MONTH); int todayMonth = todayCalendar.get(Calendar.MONTH); int ageInMonth = todayMonth - birthMonth; if (ageInMonth < 0) { ageInYear--; ageInMonth = 12 - birthMonth + todayMonth; } int birthDay = birthCalendar.get(Calendar.DATE); int todayDay = todayCalendar.get(Calendar.DATE); int ageInDay = todayDay - birthDay; if (ageInDay < 0) { ageInMonth--; // we need to calculate the age in day using previous month Calendar calendar = GregorianCalendar.getInstance(); calendar.set(Calendar.MONTH, todayMonth - 1); birthCalendar.add(Calendar.MONTH, -1); ageInDay = calendar.getActualMaximum(Calendar.DATE) - birthDay + todayDay; } if (ageInDay > todayCalendar.getActualMaximum(Calendar.DATE) / 2) ageInMonth++; ageInMonth = ageInMonth + (ageInYear * 12); return ageInMonth; } }