0
  First example: birthdate :10-01-1991(ddmmyyyy) 
                 CurrentDate :10-01-2017 

if above is the condition then I want to print 26 as current age. Second example: birthdate :25-07-1991(ddmmyyyy)
CurrentDate :10-01-2017 if above is the condition then I want to print 25 as current age.

please help me ....!!!!!!

Below is the code that i have tried.

private int calculateage(Integer day1, Integer month1, Integer year1)
{
Calendar birthCal = new GregorianCalendar(1991, 01, 10);

Calendar nowCal = new GregorianCalendar();

age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
boolean isMonthGreater = birthCal.get(Calendar.MONTH) >= nowCal
        .get(Calendar.MONTH);

boolean isMonthSameButDayGreater = birthCal.get(Calendar.MONTH) >= nowCal.get(Calendar.MONTH)
        && birthCal.get(Calendar.DAY_OF_MONTH) >= nowCal
                .get(Calendar.DAY_OF_MONTH);

if (age < 18) {
    Age = age;
}
else if (isMonthGreater || isMonthSameButDayGreater) {
    Age = age - 1;
}
return Age;

}

suraj karnati
  • 11
  • 1
  • 1
  • 3

9 Answers9

4

Use following code snippet to calculate the age:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AgeCalculator {

    public static int calculateAge(Date birthdate) {
        Calendar birth = Calendar.getInstance();
        birth.setTime(birthdate);
        Calendar today = Calendar.getInstance();

        int yearDifference = today.get(Calendar.YEAR)
                - birth.get(Calendar.YEAR);

        if (today.get(Calendar.MONTH) < birth.get(Calendar.MONTH)) {
            yearDifference--;
        } else {
            if (today.get(Calendar.MONTH) == birth.get(Calendar.MONTH)
                    && today.get(Calendar.DAY_OF_MONTH) < birth
                            .get(Calendar.DAY_OF_MONTH)) {
                yearDifference--;
            }

        }

        return yearDifference;
    }

    public static void main(String[] args) throws ParseException {
        // date format dd-mm-yyyy
        String birthdateStr = "11-01-1991";
        SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
        Date birthdate = df.parse(birthdateStr);
        System.out.println(AgeCalculator.calculateAge(birthdate));

    }
}
Devram Kandhare
  • 771
  • 2
  • 8
  • 20
3

From the reference of calculate age, use period class as following:

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);

Period p = Period.between(birthday, today);

//Now access the values as below
System.out.println(period.getDays());
System.out.println(period.getMonths());
System.out.println(period.getYears());

hope it will solve your concern.

Rahul Sharma
  • 2,867
  • 2
  • 27
  • 40
1

try this...

private String getAge(int year, int month, int day) {
    //calculating age from dob
    Calendar dob = Calendar.getInstance();
    Calendar today = Calendar.getInstance();
    dob.set(year, month, 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;
}
Sebastian
  • 417
  • 3
  • 13
1

This will be the suitable method for each condition of calculating Age from given Date --

public static String getAge(int year, int month, int day) 
{

 Calendar dob = Calendar.getInstance();

 Calendar today = Calendar.getInstance();

dob.set(year, month, day);

int today_m = today.get(Calendar.MONTH);

int dob_m = dob.get(Calendar.MONTH);

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

if (dob_m > today_m) 
{

age--;
} 
else if (dob_m == today_m) 
{

int day_today = today.get(Calendar.DAY_OF_MONTH);

int day_dob = dob.get(Calendar.DAY_OF_MONTH);
if (day_dob > day_today) {
age--;}

}
return age+"";
}

In MainActivity

public SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf2.parse("2000-03-21"));

String age=Util.getAge(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));

I am setting the given date in a calendar and sending the year,date and month to getAge() method. you can change the date format as per you requirement.

1

I know it's already an old question, but date calculation is something that always back to the discussion.

This is the method im actually using to get the exact year between two dates:

    public static String getYear(Date value) {
        Calendar date = Calendar.getInstance();
        Calendar today = Calendar.getInstance();

        date.setTime(value);

        /* get raw year between dates */
        int year = today.get(Calendar.YEAR) - date.get(Calendar.YEAR);

        /* calculate exact year */
        if (
                (date.get(Calendar.MONTH) > today.get(Calendar.MONTH)) ||
                (date.get(Calendar.MONTH) == today.get(Calendar.MONTH) && date.get(Calendar.DATE) > today.get(Calendar.DATE))
        ) {
            year--;
        }

        return year > 0 ? Integer.toString(year) : "0";
    }

-- EDIT

With JDK 8 is easier to get the year difference between dates:

(As explained in this other answer)

public static String getYear(Date value) {
    LocalDate date = value.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    int year = Period.between(date, LocalDate.now()).getYears();

    return year > 0 ? Integer.toString(year) : "0";
}

But into Android (JAVA) this only work on API 26+, so it's better to use both methods based on SDK version:

public static String getYear(Date value) {
    int year;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        LocalDate date = value.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        year = Period.between(date, LocalDate.now()).getYears();
    } else {
        Calendar date = Calendar.getInstance();
        Calendar today = Calendar.getInstance();

        date.setTime(value);

        /* get raw year between dates */
        year = today.get(Calendar.YEAR) - date.get(Calendar.YEAR);

        /* calculate exact year */
        if (
                (date.get(Calendar.MONTH) > today.get(Calendar.MONTH)) ||
                (date.get(Calendar.MONTH) == today.get(Calendar.MONTH) && date.get(Calendar.DATE) > today.get(Calendar.DATE))
        ) {
            year--;
        }
    }

    return year > 0 ? Integer.toString(year) : "0";
}
ThiagoYou
  • 308
  • 3
  • 12
1

Here i have calculated the age as year/month/day ,which works accurately to solve your problem.

  1. Inputs are taken from datepicker.

  2. Look at this code here!

        public void onClick(View v) {
            int sday=d1.getDayOfMonth();
            int smonth=d1.getMonth();
            int syear=d1.getYear();
    
            int eday=d2.getDayOfMonth();
            int emonth=d2.getMonth();
            int eyear=d2.getYear();
    
                //calculating year
                resyear = eyear - syear;
    
                //calculating month
                if (emonth >= smonth) {
                    resmonth = emonth - smonth;
                } else {
                    resmonth = emonth - smonth;
                    resmonth = 12 + resmonth;
                    resyear--;
                }
    
                //calculating date
                if (eday >= sday) {
                    resday = eday - sday;
                } else {
                    resday = eday - sday;
                    resday = 31 + resday;
                    if (resmonth == 0) {
                        resmonth = 11;
                        resyear--;
                    } else {
                        resmonth--;
                    }
                }
    
                //displaying error if calculated age is negative
                if (resday <0 || resmonth<0 || resyear<0) {
                    Toast.makeText(getApplicationContext(), "Current Date must be greater than Date of Birth", Toast.LENGTH_LONG).show();
                    t1.setText("Current Date must be greater than Date of Birth");
                }
                else {
                    t1.setText("Age: " + resyear + " years /" + resmonth + " months/" + resday + " days");
                }
            }
    
Prathamesh
  • 1,064
  • 1
  • 6
  • 16
0

Check this for android in Kotlin :

fun calculateAgeFromDob(birthDate: String,dateFormat:String): Int {

        val sdf = SimpleDateFormat(dateFormat)
        val dob = Calendar.getInstance()
        dob.time = sdf.parse(birthDate)

        val today = Calendar.getInstance()

        val curYear = today.get(Calendar.YEAR)
        val dobYear = dob.get(Calendar.YEAR)

        var age = curYear - dobYear

        try {
            // if dob is month or day is behind today's month or day
            // reduce age by 1
            val curMonth = today.get(Calendar.MONTH+1)
            val dobMonth = dob.get(Calendar.MONTH+1)
            if (dobMonth >curMonth) { // this year can't be counted!
                age--
            } else if (dobMonth == curMonth) { // same month? check for day
                val curDay = today.get(Calendar.DAY_OF_MONTH)
                val dobDay = dob.get(Calendar.DAY_OF_MONTH)
                if (dobDay > curDay) { // this year can't be counted!
                    age--
                }
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }

        return age
    }
Kabir
  • 852
  • 7
  • 11
Ashish Chaugule
  • 1,526
  • 11
  • 9
0

Use of JakeWharton library ThreeTenABP. As it's easy to use and provides awesome functionality.

Implementation

First, implement the Age Model class:

data class AgeModel(val day: Int, val month: Int, val year: Int)

Secondly, Some functionality stuff:

This function will validate the date like not greater than today's date but you could also do pass date in (currentDate) argument if you want to change the max range. Secondly, it'll also check these dates: 30-February, 31-June and return null.. And so on...

private fun getDate(year: Int, month: Int, day: Int): LocalDate? {
        return try {
            run { LocalDate.of(year, month, day) }
        } catch (e: DateTimeException) {
            null
        }
    }

fun getCalculatedAge(currentDate: LocalDate = LocalDate.now(), year: Int, month: Int, day: Int): AgeModel? {

        var curdate = currentDate.dayOfMonth
        var curmonth = currentDate.monthValue
        var curyear = currentDate.year

        val calculateDate = getDate(year, month, if (day == 0) curdate else day)
                ?: return null

        if (calculateDate > currentDate) return null

        if (day > curdate) {
            curmonth -= 1
            curdate += calculateDate.lengthOfMonth()
        }

        if (month > curmonth) {
            curyear -= 1
            curmonth += 12
        }
        return AgeModel(curdate - day, curmonth - month, curyear - year)
    }
Ali Azaz Alam
  • 1,782
  • 1
  • 16
  • 27
0

Perfect age calculate to used every side used this code in Utils folder

public static int getPerfectAge(int year, int month, int date) {

    Calendar dobCalendar = Calendar.getInstance();

    dobCalendar.set(Calendar.YEAR, year);
    dobCalendar.set(Calendar.MONTH, month);
    dobCalendar.set(Calendar.DATE, date);

    int ageInteger = 0;

    Calendar today = Calendar.getInstance();

    ageInteger = today.get(Calendar.YEAR) - dobCalendar.get(Calendar.YEAR);

    if (today.get(Calendar.MONTH) == dobCalendar.get(Calendar.MONTH)) {

        if (today.get(Calendar.DAY_OF_MONTH) < dobCalendar.get(Calendar.DAY_OF_MONTH)) {

            ageInteger = ageInteger - 1;
        }

    } else if (today.get(Calendar.MONTH) < dobCalendar.get(Calendar.MONTH)) {

        ageInteger = ageInteger - 1;

    }

    return ageInteger;
}