skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, October 24, 2012

Calculating Age using Java

Posted by Raju Gupta at 12:30 PM – 0 comments
 
To check the age from the given year.

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

public class AgeCalculation {

 /**
  * 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));
 }

 /**
  *
  * @param year --> Birth Year
  * @param month --> Birth Month
  * @param day --> Birth Day
  * @return --> Calculated Age
  */
 private static int calculateMyAge(int year, int month, int day) {
  Calendar birthCal = new GregorianCalendar(year, month, day);

  Calendar nowCal = new GregorianCalendar();

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

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

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

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

}


Labels: Java Date and Time Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger