0

I'm wondering if there is a more efficient way to take a 10 character (mm/dd/yyyy) date of birth String and calculate the age of the user as of today's date. My code works perfectly fine, but I feel like it could be more efficient.

package dates;
import java.util.*;
public class Main {
    public static void main(String[] args) {
        String dob = "02/09/1983";
        int age = age(dob);
        System.out.println(age);
    }
    public static int age(String s){
        Calendar cal = Calendar.getInstance();
        int myYear = cal.get(Calendar.YEAR);
        int myMonth = cal.get(Calendar.MONTH);
        myMonth = myMonth+1;
        int myDay = cal.get(Calendar.DAY_OF_MONTH);
        int bYear = Integer.parseInt(s.substring(s.lastIndexOf("/")+1));
        int bMonth = Integer.parseInt(s.substring(0,s.indexOf("/")));
        int bDay = Integer.parseInt(s.substring(s.indexOf("/")+1,
                                                s.lastIndexOf("/")));
        int age = 0;
        if(myMonth>=bMonth && myDay>=bDay)age = myYear - bYear;
        else age = myYear - (bYear + 1);
        return age;
    }
}
1
Contributor
1
Reply
3
Views
6 Years
Discussion Span
Last Post by Latvija13
0

Oops, I did make a mistake. Lines 20-22 need some changes.

if(myMonth>bMonth){
               age = myYear - (bYear);
        }
        else if(myMonth==bMonth&&myDay>=bDay){
                age = myYear - (bYear);
        }
        else age = myYear - (bYear + 1);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.