3

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.

akshaivk
  • 427
  • 5
  • 24
  • 1
    Related: [Why is January month 0 in Java Calendar?](http://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar) – Maroun Sep 09 '14 at 08:58
  • The months are from 0 - 11 in Calendar – nem035 Sep 09 '14 at 08:59
  • @AkshaiKumar Please clean up your Question, where you give one data example at top and a different at bottom. Consequently the answers varied in which data example they used, creating confusion. And include "today's date" you used in determining your expected result so we may compare. – Basil Bourque Sep 10 '14 at 09:24

5 Answers5

13

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.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331
3
    int da = 22;
    int mo = 10;
    int ye = 21;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.YEAR, -ye);
    cal.add(Calendar.MONTH, -mo);
    cal.add(Calendar.DAY_OF_YEAR, -da);

    System.out.println(cal.getTime());
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
talex
  • 17,973
  • 3
  • 29
  • 66
  • Can you help me to set the date from cal.getTime() to jDateChooser. I had tried this but not working. java.util.Date date = new SimpleDateFormat("dd-MM-yyyy").parse(cal.getTime().toString()); jDateChooser1.setDate(date); – akshaivk Sep 09 '14 at 09:41
  • What type jDateChooser have? – talex Sep 09 '14 at 10:18
1

You are subtracting the days first, then the months and last the years. This is wrong in my opinion because you don't know how many leap year may have been in all the years.

Try

Calendar cal = Calendar.getInstance();                       
cal.add(Calendar.YEAR, ye);   
cal.add(Calendar.MONTH, mo);  
cal.add(Calendar.DAY_OF_MONTH, da); 

doing so I get: Sun Oct 18 11:24:52 CET 1992

1

Don't reinvent the wheel. Use a decent date-time library for date-time work.

Joda-Time

You can accomplish your task in two lines of easy-to-read code using Joda-Time.

Span Of Time

The Joda-Time library has support for defining a span of time. Three classes are offered: Interval, Period, and Duration. For this purpose we need Period.

ISO 8601

Joda-Time uses the ISO 8601 standard as its default in parsing/generating strings. That standard defines this format for durations (what Joda-Time calls Period) this way: PnYnMnDTnHnMnS. The P starts every instance, and the T separates the date portion from the time-of-day portion. You can use this kind of string to construct a Period object, or you can pass numbers for years, months, days, and so on.

Time Zone

If you want more accuracy, you should specify the time zone intended by your years-months-days count. Results may vary by a day as the date depends on the time zone. A new day dawns earlier in Paris than in Montréal.

Example Code

Example code in Joda-Time 2.4.

LocalDate now = LocalDate.now( DateTimeZone.forID( "America/Montreal" ) );
Period age = new Period( "P21Y10M22D" ); // 21 years, 10 months, and 22 days. Or: new Period( 21, 10, 22…
LocalDate birth = now.minus( age );

Dump to console.

System.out.println( "now: " + now );
System.out.println( "age: " + age );
System.out.println( "birth: " + birth );

When run.

now: 2014-09-10
age: P21Y10M22D
birth: 1992-10-19
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0
import java.time.LocalDate;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class Main {

public static void main(String[] args){
    String ageDay = "31";
    String ageMonth = "4";
    String ageYear = "10";
    LocalDate resultDOB = findDateOfBirth(ageYear,ageMonth,ageDay);
    System.out.println(resultDOB);

}

private static LocalDate findDateOfBirth(String ageYear, String ageMonth, String ageDay) {
    int ageYearInInt = convertAgeNumberToInt(ageYear);
    int ageMonthInInt = convertAgeNumberToInt(ageMonth);
    int ageDayInInt = convertAgeNumberToInt(ageDay);
    LocalDate today = LocalDate.now();
    int dobYear  = today.getYear() - ageYearInInt;
    Set<Integer> monthsHaving30Days = Collections.EMPTY_SET;
    Collections.addAll(monthsHaving30Days = new HashSet<Integer>(), 1, 3, 5, 7, 10, 12);
    Set<Integer> monthsHaving31Days= Collections.EMPTY_SET;
    Collections.addAll(monthsHaving31Days = new HashSet<Integer>(), 4, 6, 9, 11);
    int dobMonth = today.getMonthValue() - ageMonthInInt;
    if(dobMonth<=0){
        dobMonth = 12 - Math.abs(dobMonth);
        dobYear--;
    }
    int dobDay   = today.getDayOfMonth() - ageDayInInt;

    if(dobDay<=0){
        dobMonth--;
        if(dobMonth == 2){
           if(today.getMonthValue() == 3){
               if(isLeapYear(dobYear)){
                   dobDay = 29 - Math.abs(dobDay);
               }else{
                   dobDay = 28 - Math.abs(dobDay);
               }
           } else{
               dobDay = 31 - Math.abs(dobDay);
           }
        }
        if(dobMonth<=0){
            dobYear--;
            dobMonth = 12 - Math.abs(dobMonth);
        }
        if(monthsHaving31Days.contains(dobMonth)){
            dobDay = 31 - Math.abs(dobDay);
        }
        if(monthsHaving30Days.contains(dobMonth)){
            dobDay = 30 - Math.abs(dobDay);
        }
    }
   // System.out.println(dobDay + "/" + dobMonth + "/"+ dobYear);
    return LocalDate.of(dobYear, dobMonth, dobDay);
}

private static boolean isLeapYear(int year) {
    boolean leap = false;
    if (year % 4 == 0) {
        if (year % 100 == 0) {
            if (year % 400 == 0) {
                leap = true;
            }
            else {
                leap = false;
            }
        }
        else {
            leap = true;
        }
    }
    else {
        leap =  false;
    }
    return leap;
}

private static int convertAgeNumberToInt(String ageNumberInString) {
    int ageNumberInInt;
    if(!ageNumberInString.isEmpty() && isStringNumber(ageNumberInString)){
        ageNumberInInt  = Integer.parseInt(ageNumberInString);
    }else{
        ageNumberInInt  = 0;
    }

    return ageNumberInInt;
}

private static boolean isStringNumber(String string) {
    if(string.isEmpty()){
        return false;
    }
    Integer numberVal;
    try{
        numberVal = Integer.parseInt(string);
    } catch (NumberFormatException nfe){
        return false;
    }
    return true;
}

}
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 17 '21 at 07:25
  • Why so enormously complicated? The simple accepted answer works very fine. – Ole V.V. Nov 17 '21 at 08:46