Get Age from Date of Birth in Java Android

Here is how to get a user’s age from date of birth

If you need get a user’s age from a given date of birth string, this code below can be used for that

The date of birth string must be in DD/MM/YYYY format

  private int getAge(String dobString){

        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        try {
            date = sdf.parse(dobString);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if(date == null) return 0;

        Calendar dob = Calendar.getInstance();
        Calendar today = Calendar.getInstance();

        dob.setTime(date);

        int year = dob.get(Calendar.YEAR);
        int month = dob.get(Calendar.MONTH);
        int day = dob.get(Calendar.DAY_OF_MONTH);

        dob.set(year, month+1, day);

        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

        if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
            age--;
        }
        return age;
}

When you call this, it will return the age based on the string you provided.

If you need any help or you need any type of android apps and games developed, we can develop it for you, just contact us 

Related Posts

How to Export Project Zip from Android Studio

How to Export Source Code ZIP in Android Studio Sometimes, you will need export the source code of your android studio app project, to share it with…

Fix Plugin [id: ‘com.android.application’, version: ‘7.1.3’, apply: false] was not found in any of the following sources

Here is how to fix Plugin [id: ‘com.android.application’, version: ‘7.1.3’, apply: false] was not found in any of the following sources This error is caused by mismatching…

How to Check if String Array Contains a Specific String in Android

Here is how to get a specific value or String from Array in Android To check if a string array contains a specific string, you can use…

Make Android WebView Support Razorpay Payment

How to Support Razorpay Payment and UPI in Android WebView? Android webview is inexpensive and easy way to make apps for websites. But to support some specific…

Make Android Webview Support PayTM Google Pay PhonePe UPI

GooglePay, Phonpe and PayTM support in Android WebView If you have built an android app for your new ecommerce website or any other website that needs accept…

Leave a Reply

Your email address will not be published. Required fields are marked *