Pages Navigation Menu

Coding is much easier than you think

Calculating Age using Java

Calculating Age using Java

 
To calculate age from the given year , the following sippnet of code can be used.
 

package com.simplecode;

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

public class CalculateAge {

	
	 // Month Representations
	 
	static final int JAN = 0;
	static final int FEB = 1;
	static final int MAR = 2;
	static final int APR = 3;
	static final int MAY = 4;
	static final int JUN = 5;
	static final int JUL = 6;
	static final int AUG = 7;
	static final int SEP = 8;
	static final int OCT = 9;
	static final int NOV = 10;
	static final int DEC = 11;

	public static void main(String[] args) {
		System.out.println("Born In 1982-JUL-11. Current Age: "
				+ calculateMyAge(1982, JUL, 11));
		System.out.println("Born In 1957-DEC-09. Current Age: "
				+ calculateMyAge(1957, DEC, 9));
	}

	private static int calculateMyAge(int year, int month, int day) {
		Calendar birthCal = new GregorianCalendar(year, month, day);

		Calendar presentCal = new GregorianCalendar();

		int age = presentCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);

		boolean isMonthGreater = birthCal.get(Calendar.MONTH) >= presentCal
				.get(Calendar.MONTH);

	 boolean isMonthSameButDayGreater = birthCal.get(Calendar.MONTH) == presentCal
				.get(Calendar.MONTH)
				&& birthCal.get(Calendar.DAY_OF_MONTH) > presentCal
						.get(Calendar.DAY_OF_MONTH);

		if (isMonthGreater || isMonthSameButDayGreater) {
			age = age - 1;
		}
		return age;
	}

}

 

dwd2
Download It -€“ CalculateAge

 

About Mohaideen Jamil