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;
    }
}

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);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.