Skip to content
Advertisement

Finding date of birth from age in java

Hello all I am creating a program for finding the date of birth when the exact age is given. For example if age of a man is 21 years 10 months and 22 days(up to current date) how can i find the exact date of birth. I will be thankful if anyone help me with isuue.

What i tried is here.

here d,m and y are text field for days months and years.

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            int da = Integer.parseInt(d.getText());
            da = -da;
            int mo = Integer.parseInt(m.getText());
            mo = -mo;        
            int ye = Integer.parseInt(y.getText());
            ye = -ye;
            SimpleDateFormat ddd = new SimpleDateFormat("dd");
            SimpleDateFormat mmm = new SimpleDateFormat("MM");
            SimpleDateFormat yyy = new SimpleDateFormat("yyyy");
            Calendar cal = Calendar.getInstance();                       
            cal.getTime();
            cal.add(Calendar.DATE, da);
             cal.set(Integer.parseInt(yyy.format(cal.getTime())), Integer.parseInt(mmm.format(cal.getTime())), Integer.parseInt(ddd.format(cal.getTime())));
            cal.add(cal.MONTH, mo);cal.set(Integer.parseInt(yyy.format(cal.getTime())), Integer.parseInt(mmm.format(cal.getTime())), Integer.parseInt(ddd.format(cal.getTime())));
            cal.add(cal.YEAR, ye);
            System.out.println(getDate(cal));
        }

My problem is if I enter 21 year 10 months and 22 days as the age of a person the date given by compiler is 18/12/1992 but actual date should be 17/10/1992. Please help me with this issue.

Advertisement

Answer

Here is Java 8 solution implemented by Date & Time API:

int dobYear = 21;
int dobMonth = 10;
int dobDay = 22;

LocalDate now = LocalDate.now();
LocalDate dob = now.minusYears(dobYear)
        .minusMonths(dobMonth)
        .minusDays(dobDay);

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
System.out.println(dob.format(formatter));

Output: 18/10/1992.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement