Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do i use dateformat to automate calculation of age base now date.?

Status
Not open for further replies.

flyclassic22

Technical User
Oct 1, 2002
54
SG
hi,
let's say i've a string call "19/03/1964"
anyone has an example on how do i make use of dateformat or date to calculate the age based on today's date?

Your help will be greated appreciated. thanks
 
Here are a couple of ways to do what you want...
Code:
public class AgeCal{
public static void main (String[] args) {
  DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
  Date dob = null;
  if (args.length != 1)
  {
	  System.out.println ("Please enter your date of birth");

  }
  else
  {
  try {
      dob = df.parse(args[0]);
  } catch (ParseException pe) {
      System.out.println("Date format invalid: " + pe);
      return;
  }
  System.out.println("Age is: " + getAge(dob));
}
}


public static int getAge(Date dob) {
      Calendar caldob = Calendar.getInstance();
      caldob.setTime(dob);
      Calendar currentDate = Calendar.getInstance();

      int diffyear = currentDate.get(Calendar.YEAR) -  caldob.get(Calendar.YEAR);
      int diffmonth = currentDate.get(Calendar.MONTH) - caldob.get(Calendar.MONTH);
      int diffday = currentDate.get(Calendar.DATE) - caldob.get(Calendar.DATE);

      if ( diffmonth < 0 || (diffmonth == 0 && diffday < 0))  {
           diffyear -= 1;
      }
      return diffyear;
}
}
*****Another Ways...Found this on java.sun.com******
Code:
String dateOfBirth = &quot;03/19/1964&quot;;
        Calendar currentDate = new GregorianCalendar();
        SimpleDateFormat sdf = new SimpleDateFormat(&quot;MM/dd/yyyy&quot;);
        Date date = null;
        try {
            date = sdf.parse(dateOfBirth);
        } catch (ParseException pe) {
            System.out.println(&quot;Bad date - &quot; + pe);
        }
        Calendar birthDate = new GregorianCalendar();
        birthDate.setTime(date);
        Calendar testDate = new GregorianCalendar();
        testDate.setTime(date);

        int approximateAge = currentDate.get(Calendar.YEAR)
                                                - birthDate.get(Calendar.YEAR);
        testDate.add(Calendar.YEAR, approximateAge);
        int actualAge = (testDate.after(currentDate))
            ? approximateAge - 1 : approximateAge;

        System.out.println(&quot;Current date = &quot; + sdf.format(currentDate.getTime()));
        System.out.println(&quot;Birth date = &quot; + sdf.format(birthDate.getTime()));
        System.out.println(&quot;Age = &quot; + actualAge);

*** Another ways...I found this way while doing a search from java.sun.com site***

Code:
import java.io.*;
import java.util.*;

public class ComputeAge1 {
   public static void main(String args[])throws IOException {
      String inString;
      int bYear = 0, bMonth = 0, bDay = 0;
      InputStreamReader is = new InputStreamReader(System.in);
      BufferedReader stdin = new BufferedReader(is);
      boolean valid=false;
      // V.V.
      while (!valid) {
         try {
            System.out.println(&quot;Please enter the year of your birth:&quot;);
            inString = stdin.readLine();
            bYear = Integer.parseInt(inString);
            System.out.println(&quot;Please enter the month of your birth:&quot;);
            inString = stdin.readLine();
            bMonth = Integer.parseInt(inString);
            System.out.println(&quot;Please enter the Day of your birth:&quot;);
            inString = stdin.readLine();
            bDay = Integer.parseInt(inString);
            if (bYear<1800) System.out.println(&quot;Year must be >=1800&quot;);
            else {
               GregorianCalendar toDay = new GregorianCalendar();
               GregorianCalendar birthDay = new GregorianCalendar(bYear, bMonth-1, bDay);
               // month parameter is based on 0 to 11 -- V.V.
               int birthYear = birthDay.get(Calendar.YEAR);
               int birthMonth = birthDay.get(Calendar.MONTH);
               int birthDDay = birthDay.get(Calendar.DATE);
               boolean inputError=false;     // check for other bad inputs
               if (birthYear!=bYear) inputError=true;
               if (birthMonth+1!=bMonth) inputError=true;
               if (birthDDay!=bDay) inputError=true;
               if (inputError) System.out.println(&quot;You've entered an incorrect date&quot;);
               else {
                  System.out.println(&quot;You are born in year &quot; + birthYear);
                  System.out.println(&quot;You are born in the month &quot; + (birthMonth+1));
                  System.out.println(&quot;You are born on the day &quot; + birthDDay);
                  int toDayYear = toDay.get(Calendar.YEAR);
                  int toDayMonth = toDay.get(Calendar.MONTH);
                  int toDayDay = toDay.get(Calendar.DATE);
                  int yearAge = toDayYear - birthYear;
                  int monthAge = 0;
                  if (toDayMonth >= birthMonth) {                  // V.V.
                     monthAge = toDayMonth - birthMonth;
                  } else {
                     yearAge--;
                     monthAge = 12 +toDayMonth - birthMonth;
                  }
                  int dayAge = toDayDay - birthDDay ;
                  if (toDayDay >= birthDDay) {                     // V.V.
                     dayAge = toDayDay - birthDDay;
                  } else {
                     monthAge--;
                     toDay.add(Calendar.MONTH,-1);                 // V.V.
                     dayAge = toDay.getActualMaximum(Calendar.DAY_OF_MONTH)+ toDayDay - birthDDay;       // V.V.
                  }
                  printAgeData(yearAge, monthAge, dayAge);
                  //call to the method that print age data
                  valid=true;
               }
            }
         } catch (NumberFormatException exception) {               // V.V.
            System.out.println(&quot;Non-numeric data entered&quot;);        // V.V.
         }
      }
   }     //main
   public static void printAgeData(int yAge, int mAge, int dAge) {
      StringBuffer year = new StringBuffer(&quot; year&quot;);
      StringBuffer month = new StringBuffer(&quot; month&quot;);
      StringBuffer day = new StringBuffer(&quot; day&quot;);
      if (yAge > 1)year.append(&quot;s&quot;);            // V.V.
      if (mAge > 1)month.append(&quot;s&quot;);           // V.V.
      if (dAge > 1)day.append(&quot;s&quot;);             // V.V.
      System.out.println(&quot;Your age is : &quot; + yAge + year);
      System.out.println(&quot;Your age is : &quot; + mAge + month);
      System.out.println(&quot;Your age is : &quot; + dAge + day);
   }         //printAgeData
}      //class
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top