calculating the age from current date

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • karthickkuchanur
    New Member
    • Dec 2007
    • 156

    calculating the age from current date

    Hai sir,
    i assigned to calculate the age from current date ,i have the date of birth of employee from that i have to calculate the age dynamically,
    i refer to google it was confusing me .please give some idea to do sir
  • hirak1984
    Contributor
    • Jan 2007
    • 316

    #2
    Originally posted by karthickkuchanu r
    Hai sir,
    i assigned to calculate the age from current date ,i have the date of birth of employee from that i have to calculate the age dynamically,
    i refer to google it was confusing me .please give some idea to do sir
    so what is the problem?
    are you finding it difficult to calculate? or to write the code?
    first learn the calculation.
    tell us how would you calculate if the question was there in your mathematics class? post the formula.

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by karthickkuchanu r
      Hai sir,
      i assigned to calculate the age from current date ,i have the date of birth of employee from that i have to calculate the age dynamically,
      i refer to google it was confusing me .please give some idea to do sir
      Have a look at java.util.Grego rianCalendar, try some code, and post again if you still have problems.

      Comment

      • karthickkuchanur
        New Member
        • Dec 2007
        • 156

        #4
        Originally posted by r035198x
        Have a look at java.util.Grego rianCalendar, try some code, and post again if you still have problems.
        ok sir i will try tot do that

        Comment

        • karthickkuchanur
          New Member
          • Dec 2007
          • 156

          #5
          Originally posted by hirak1984
          so what is the problem?
          are you finding it difficult to calculate? or to write the code?
          first learn the calculation.
          tell us how would you calculate if the question was there in your mathematics class? post the formula.
          to develope the code i have the set code in google but i cant able to study that

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #6
            Originally posted by karthickkuchanu r
            to develope the code i have the set code in google but i cant able to study that
            What do you mean by that?

            Comment

            • karthickkuchanur
              New Member
              • Dec 2007
              • 156

              #7
              Originally posted by r035198x
              What do you mean by that?
              Code:
              import java.util.*;
              import java.io.*;
              
              public class AgeCalculation{
                public static void main(String[] args) throws IOException{
                  int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays;
                  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                  Calendar cd = Calendar.getInstance();
                  try{
                    System.out.print("Enter year of your date of birth : ");
                    year = Integer.parseInt(in.readLine());
                    if(year > cd.get(Calendar.YEAR)){
                      System.out.print("Invalid date of birth.");
                      System.exit(0);
                    }
                    System.out.print("Enter month of your date of birth : ");
                    month = Integer.parseInt(in.readLine());
                    if(month < 1 || month > 12){
                      System.out.print("Please enter monthe between 1 to 12.");
                      System.exit(0);
                    }
                    else{
                      month--;
                      if(year == cd.get(Calendar.YEAR)){
                        if(month > cd.get(Calendar.MONTH)){
                          System.out.print("Invalid month!");
                          System.exit(0);
                        }
                      }
                    }
                    System.out.print("Enter day of your date of birth : ");
                    day = Integer.parseInt(in.readLine());
                    if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || 
              month == 9 || month == 11){
                      if(day > 31 || day < 1){
                        System.out.print("Please enter day between 1 to 31.");
                        System.exit(0);
                      }
                    }
                    else if(month == 3 || month == 5 || month == 8 || month == 10){
                      if(day > 30 || day < 1){
                        System.out.print("Please enter day between 1 to 30.");
                        System.exit(0);
                      }
                    }
                    else{
                      if(new GregorianCalendar().isLeapYear(year)){
                        if(day < 1 || day > 29){
                          System.out.print("Please enter day between 1 to 29.");
                          System.exit(0);
                        }
                      }
                      else if(day < 1 || day > 28){
                        System.out.print("Please enter day between 1 to 28.");
                        System.exit(0);
                      }
                    }
                    if(year == cd.get(Calendar.YEAR)){
                      if(month == cd.get(Calendar.MONTH)){
                        if(day > cd.get(Calendar.DAY_OF_MONTH)){
                          System.out.print("Invalid date!");
                          System.exit(0);
                        }
                      }
                    }
                  }
                  catch(NumberFormatException ne){
                    System.out.print(ne.getMessage() + " is not a legal entry!");
                    System.out.print("Please enter number.");
                    System.exit(0);
                  }
                  Calendar bd = new GregorianCalendar(year, month, day);
                  ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
                  if(cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
                    ageYears--;
                    ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH));
                    if(day > cd.get(Calendar.DAY_OF_MONTH)){
                      ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
                    }
                    else if(day < cd.get(Calendar.DAY_OF_MONTH)){
                      ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
                    }
                    else{
                      ageDays = 0;
                    }
                  }
                  else if(cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
                    ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
                    if(day > cd.get(Calendar.DAY_OF_MONTH))
                      ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
                    else if(day < cd.get(Calendar.DAY_OF_MONTH)){
                      ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
                    }
                    else
                      ageDays = 0;
                  }
                  else{
                    ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
                    ageMonths = 0;
                    ageDays = 0;
                  }
                  System.out.print("Age of the person : " + ageYears + " year, " + ageMonths + 
              " months and " + ageDays + " days.");
                }
              }

              this the code i have but i want to simply by this please help me

              Comment

              • r035198x
                MVP
                • Sep 2006
                • 13225

                #8
                What did you say the problem is?
                Does the code compile sucessfully?
                Does it give the correct results?

                Comment

                • hirak1984
                  Contributor
                  • Jan 2007
                  • 316

                  #9
                  Originally posted by karthickkuchanu r
                  Code:
                      Calendar bd = new GregorianCalendar(year, month, day);
                      ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
                      if(cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
                        ageYears--;
                        ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH));
                        if(day > cd.get(Calendar.DAY_OF_MONTH)){
                          ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
                        }
                        else if(day < cd.get(Calendar.DAY_OF_MONTH)){
                          ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
                        }
                        else{
                          ageDays = 0;
                        }
                      }
                      else if(cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
                        ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
                        if(day > cd.get(Calendar.DAY_OF_MONTH))
                          ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
                        else if(day < cd.get(Calendar.DAY_OF_MONTH)){
                          ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
                        }
                        else
                          ageDays = 0;
                      }
                      else{
                        ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
                        ageMonths = 0;
                        ageDays = 0;
                      }
                      System.out.print("Age of the person : " + ageYears + " year, " + ageMonths + 
                  " months and " + ageDays + " days.");
                    }
                  }

                  this the code i have but i want to simply by this please help me
                  Look.
                  first of all dont randomly pick up codes from the net. The code you posted is written by a professional, abiding by all the standards of code writing.
                  But not so affluent as you are, it is bound to look puzzling to you.
                  You need not take any user input at this point. Hard code a date in your main().
                  and try to calculated age using it.
                  use the formula they have used in the above part of your code.
                  tell us what errors you got in doing this.

                  Comment

                  • karthickkuchanur
                    New Member
                    • Dec 2007
                    • 156

                    #10
                    Originally posted by hirak1984
                    Look.
                    first of all dont randomly pick up codes from the net. The code you posted is written by a professional, abiding by all the standards of code writing.
                    But not so affluent as you are, it is bound to look puzzling to you.
                    You need not take any user input at this point. Hard code a date in your main().
                    and try to calculated age using it.
                    use the formula they have used in the above part of your code.
                    tell us what errors you got in doing this.
                    ok sir i will try to do my best

                    Comment

                    • JosAH
                      Recognized Expert MVP
                      • Mar 2007
                      • 11453

                      #11
                      @OP: maybe just for the fun of it (or a better understanding of dates), google for
                      Zeller's congruence.

                      kind regards,

                      Jos

                      Comment

                      • hirak1984
                        Contributor
                        • Jan 2007
                        • 316

                        #12
                        Originally posted by JosAH
                        @OP: maybe just for the fun of it (or a better understanding of dates), google for
                        Zeller's congruence.

                        kind regards,

                        Jos

                        wow!!!
                        that was gr8 man. really interesting.
                        thnx JosAH

                        Comment

                        • poloolop
                          New Member
                          • Jun 2010
                          • 1

                          #13
                          Age calculator (class)

                          Guys, here is the easiest code of age calculator...


                          Code:
                          import java.util.Calendar;
                          import java.text.SimpleDateFormat;
                          
                          public class age {
                           
                           private float year;
                           private float age;
                           private float month;
                           private float yearx;
                           private float monthx;
                           private float dayx;
                           private float day;
                           private float mon;
                           private String yearFormat = "yyyy";
                           private String monthFormat = "MM";
                           private String dayFormat = "dd";
                           	 
                          	public age (int d ,int m, int y){
                          		float curYear = Integer.parseInt(curDate(yearFormat));
                          		float curMonth = Float.parseFloat(curDate(monthFormat));
                          		float curDay = Float.parseFloat(curDate(dayFormat));
                          		year = y;
                          		month = m;
                          		day = d;
                          	 	
                          	 	yearx = curYear - year;
                          	 	monthx = curMonth - month;
                          	 	dayx = curDay - day;
                          	 	age = yearx +  monthx/12;
                          	 	if( monthx < 0) {
                          	 		mon = 12-(Math.abs(monthx));	
                          	 	}
                          	 	else {
                          	 		mon = Math.abs(monthx);
                          	 	}
                          	 	
                          	}
                          	  
                           
                            static String curDate(String format) {
                              Calendar cal = Calendar.getInstance();
                              SimpleDateFormat sdf = new SimpleDateFormat(format);
                              return sdf.format(cal.getTime());
                          
                            }
                            
                            
                            
                            public String toString () {
                            
                            	return String.format("Age: %.0fyears %.0fmonths %.0f%s", Math.floor(age) ,  Math.abs((dayx>=0? mon:mon-1)) , (dayx>=0? dayx:30+dayx), ((Math.abs(dayx))>1? "days":"day") );
                            }
                            
                          }

                          Comment

                          • Ramil Grayda
                            New Member
                            • Jul 2010
                            • 1

                            #14
                            Java method to compute for duration in years, months and days

                            Code:
                            /**
                            	 * Computes the duration between an input date and date today and returns
                            	 * the value in years, months and days
                            	 * 
                            	 * @param month
                            	 *            - input month
                            	 * @param day
                            	 *            - input day
                            	 * @param year
                            	 *            - input year
                            	 * @return duration in years, months and days
                            	 */
                            	public String getDuration(int month, int day, int year) throws Exception {
                            		/* input calendar date */
                            		month--; // following the 0-based rule
                            		Calendar cal = new GregorianCalendar(year, month, day);
                            
                            		/* date today */
                            		java.util.Date today = new java.util.Date();
                            
                            		/* year now */
                            		SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
                            		int intYear = Integer.parseInt(sdfYear.format(today));
                            
                            		/* month now */
                            		SimpleDateFormat sdfMonth = new SimpleDateFormat("MM");
                            		int intMonth = Integer.parseInt(sdfMonth.format(today));
                            		intMonth--; // following the 0-based rule
                            
                            		/* day now */
                            		SimpleDateFormat sdfDay = new SimpleDateFormat("dd");
                            		int intDay = Integer.parseInt(sdfDay.format(today));
                            
                            		/* calendar date now */
                            		Calendar now = new GregorianCalendar(intYear, intMonth, intDay);
                            
                            		/* years duration */
                            		int yyyy = intYear - year;
                            
                            		/* array of days in 12 months */
                            		int[] months = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
                            
                            		/*
                            		 * an indicator if given date has already occurred. (-1) - if given date
                            		 * is greater than the current date; 0 - if given date has not yet
                            		 * occurred or if it's equal to the current date.
                            		 */
                            		int factor = 0;
                            
                            		int mm = 0; // month duration
                            
                            		int dd = 0; // day duration 
                            
                            		/* determine if given date is greater than or equal to the current date */
                            		if ((month > intMonth) || (month == intMonth && day > intDay)) {
                            			factor = -1;
                            			yyyy += factor;
                            		}
                            
                            		/* throw if any of the following exceptions occur */
                            		if (month > 12) {
                            			throw new Exception("Invalid input month");
                            		} else if (day > months[month]) {
                            			throw new Exception("Invalid input day");
                            		} else if (yyyy < 0) {
                            			throw new Exception("Invalid input date");
                            		}
                            
                            		/*
                            		 * if the given date has already passed or if it's equal to the current
                            		 * date
                            		 */
                            		if (factor == 0) {
                            			// compute for days in between the given and the current date
                            			dd = now.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR);
                            			/* determine if the current year is a leap year */
                            			if ((intYear % 4) == 0) {
                            				months[1]++; // increment the days in February by 1
                            			}
                            			/*
                            			 * compute for day duration and month duration between the given
                            			 * date and the given day of the current month
                            			 */
                            			for (int i = month; i <= intMonth; i++) {
                            				if (dd >= months[i]) {
                            					dd -= months[i];
                            					mm++;
                            				}
                            			}
                            			/*
                            			 * if computed month duration is more than 12, finalize values for
                            			 * year and month duration
                            			 */
                            			if (mm >= 12) {
                            				yyyy += (mm / 12);
                            				mm %= 12;
                            			}
                            		} else { // if the given date is greater than the current date
                            			intYear--; // derive previous year
                            			/* set Calendar date for December 31 of the previous year */
                            			Calendar prev = new GregorianCalendar(intYear, 11, 31);
                            			/*
                            			 * compute the days in between the given date last year and the
                            			 * current date
                            			 */
                            			dd = (prev.get(Calendar.DAY_OF_YEAR) - cal
                            					.get(Calendar.DAY_OF_YEAR))
                            					+ now.get(Calendar.DAY_OF_YEAR);
                            			/* determine if previous year is a leap year */
                            			if ((intYear % 4) == 0) {
                            				months[1]++; // increment the days in February by 1
                            			}
                            			/*
                            			 * compute for day duration and month duration between the given
                            			 * date and the given day in December of the previous year
                            			 */
                            			for (int i = month; i <= 11; i++) {
                            				if (dd >= months[i]) {
                            					dd -= months[i];
                            					mm++;
                            				}
                            			}
                            			intYear++; // set the value back to the current year
                            			/* determine if current year is a leap year */
                            			if ((intYear % 4) == 0) {
                            				months[1]++; // increment the days in February by 1
                            			}
                            			/*
                            			 * compute for day duration and month duration between the given day
                            			 * in January of the current year and the current date
                            			 */
                            			for (int i = 0; i <= intMonth; i++) {
                            				if (dd >= months[i]) {
                            					dd -= months[i];
                            					mm++;
                            				}
                            			}
                            			/*
                            			 * if computed month duration is more than 12, finalize values for
                            			 * year and month duration
                            			 */
                            			if (mm >= 12) {
                            				yyyy += (mm / 12);
                            				mm %= 12;
                            			}
                            		}
                            
                            		/* computed duration in years, months and days */
                            		return yyyy + " Year(s), " + mm + " Month(s), and " + dd + " Day(s) ";
                            	}
                            Last edited by Niheel; Jul 28 '10, 05:53 AM. Reason: please use code tags to display code

                            Comment

                            • Marco W

                              #15
                              Code:
                              /**
                              * Another age calculater which calcultes the age in years (on the minute)
                              * Just a quickly made (5 min) piece of code for who ever is interested
                              **/
                              
                              // Initialize a birth date calendar and set the birth date
                              Calendar birthDateCalendar = Calendar.getInstance();
                              birthDateCalendar.setTimeInMillis((new SimpleDateFormat("dd-MM-yyyy HH:mm").parse("13-12-1979 14:39").getTime()));
                              
                              // Initialize the age with -1 : stating a future birth date
                              int ageInYears = -1;
                              
                              // Add a year until the birthdate equals now
                              for(Calendar now = Calendar.getInstance(); birthDateCalendar.compareTo(now) < 0 ; birthDateCalendar.add(Calendar.YEAR, 1))
                              {
                                    ageInYears += 1;
                              }
                              
                              // Here's the age in years
                              System.err.println(ageInYears);
                              Last edited by MMcCarthy; Oct 28 '10, 05:47 PM. Reason: added code tags

                              Comment

                              Working...