Wednesday, July 31, 2013

Java Age Calculate

 public static String getAge(String dateOfBirth) {
       int age;
       int age_m;
       int age_d;
      // String dob = "1984-09-20";
       String dob = dateOfBirth;

            //TAKE SUBSTRINGS OF THE DOB SO SPLIT OUT YEAR, MONTH AND DAY
            //INTO SEPERATE VARIABLES
            int yearDOB = Integer.parseInt(dob.substring(0, 4));
            int monthDOB = Integer.parseInt(dob.substring(5, 7));
            int dayDOB = Integer.parseInt(dob.substring(8, 10));

            //CALCULATE THE CURRENT YEAR, MONTH AND DAY
            //INTO SEPERATE VARIABLES
            DateFormat dateFormat = new SimpleDateFormat("yyyy");
            java.util.Date date = new java.util.Date();
            int thisYear = Integer.parseInt(dateFormat.format(date));

            dateFormat = new SimpleDateFormat("MM");
            date = new java.util.Date();
            int thisMonth = Integer.parseInt(dateFormat.format(date));

            dateFormat = new SimpleDateFormat("dd");
            date = new java.util.Date();
            int thisDay = Integer.parseInt(dateFormat.format(date));

            //CREATE AN AGE VARIABLE TO HOLD THE CALCULATED AGE
            //TO START WILL – SET THE AGE EQUEL TO THE CURRENT YEAR MINUS THE YEAR
            //OF THE DOB
            age = thisYear - yearDOB;

            //IF THE CURRENT MONTH IS LESS THAN THE DOB MONTH
            //THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
            //BIRTHDAY YET THIS YEAR
            if(thisMonth < monthDOB){
                age_m = monthDOB-thisMonth;
            }else{
            age_m = thisMonth-monthDOB;
            }
            if(thisMonth == monthDOB){
                age_m = 0;
            }
            //IF THE MONTH IN THE DOB IS EQUEL TO THE CURRENT MONTH
            //THEN CHECK THE DAY TO FIND OUT IF THEY HAVE HAD THEIR
            //BIRTHDAY YET. IF THE CURRENT DAY IS LESS THAN THE DAY OF THE DOB
            //THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
            //BIRTHDAY YET THIS YEAR
            if(thisDay < dayDOB){
            age_d = dayDOB - thisDay;
            }else{
            age_d =  thisDay - dayDOB;  
            }

            if(thisDay == dayDOB){
            age_d = 0;
            }

            //THE AGE VARIBALE WILL NOW CONTAIN THE CORRECT AGE
            //DERIVED FROMTHE GIVEN DOB
            System.out.println(age);
            String p = age + " Year " + age_m + " Month " + age_d + " Days ";
            return p;
    }

No comments:

Post a Comment