Calculate age from BirthDate

2020-06-03 01:25发布

I have DatePicker Dialog, When I select date at that time I want to calculate age it's working but when I select date of current year at that time it showing the -1 age instead of 0 then how can solve this? Please help me to solve it. My code is below:

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

        GregorianCalendar cal = new GregorianCalendar();
        int y, m, d, noofyears;

        y = cal.get(Calendar.YEAR);// current year ,
        m = cal.get(Calendar.MONTH);// current month
        d = cal.get(Calendar.DAY_OF_MONTH);// current day
        cal.set(year, month, day);// here ur date
        noofyears = (int) (y - cal.get(Calendar.YEAR));
        LOGD("Age......", String.valueOf(noofyears));

        if ((m < cal.get(Calendar.MONTH)) || ((m == cal.get(Calendar.MONTH)) && (d < cal.get(Calendar.DAY_OF_MONTH)))) {
            --noofyears;
        }
        LOGD("Age......", String.valueOf(noofyears));
        if (noofyears != 0) {
            ageCount = noofyears;
        } else {
            ageCount = 0;
        }
        if (noofyears < 0)
            throw new IllegalArgumentException("age < 0");
        return noofyears;
    }

15条回答
老娘就宠你
2楼-- · 2020-06-03 01:48

java.time

For the sage of completeness and being up-to-date concerning packages, here is the way using java.time (Java 8+).

Java

public int getAge(int year, int month, int dayOfMonth) {
    return Period.between(
                LocalDate.of(year, month, dayOfMonth),
                LocalDate.now()
            ).getYears();
}

Kotlin

fun getAge(year: Int, month: Int, dayOfMonth: Int): Int {
    return Period.between(
                LocalDate.of(year, month, dayOfMonth),
                LocalDate.now()
            ).getYears()
}

Both snippets need the following imports from java.time:

import java.time.LocalDate;
import java.time.Period

It's not recommended to use java.util.Date and java.util.Calendar anymore except from situations where you have to involve considerably large amounts of legacy code.

See also Oracle Tutorial.

For projects supporting Java 6 or 7, this functionality is available via the ThreeTenBP,
while there is special version, the ThreeTenABP for API levels below 26 in Android.

查看更多
何必那么认真
3楼-- · 2020-06-03 01:49
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;
}
查看更多
不美不萌又怎样
4楼-- · 2020-06-03 01:52

Here is a Kotlin extension of the Date class returning the age corresponding to a Date object

val Date.age: Int
get() {
    val calendar = Calendar.getInstance()
    calendar.time = Date(time - Date().time)
    return 1970 - (calendar.get(Calendar.YEAR) + 1)
}

It is compatible for all Android versions. If you wonder what '1970' is, that's the Unix Epoch. The timestamp is 0 on January 1, 1970.

查看更多
【Aperson】
5楼-- · 2020-06-03 01:53
      private void calculateAge() {
    age.calcualteYear();
    age.calcualteMonth();
    age.calcualteDay();
    age.calculateMonths();
    age.calTotalWeeks();
    age.calTotalHours();
    age.calTotalMins();
    age.calTotalSecs();
    age.calTotalMilsecs();
    // Toast.makeText(getContext(), "click the resulted button"+age.getResult() , Toast.LENGTH_SHORT).show();
    result.setText("AGE (DD/MM/YY) :" + age.getResult());
}

after that create one class

 public class AgeCalculation {
private int startYear;
private int startMonth;
private int startDay;
private int endYear;
private int endMonth;
private int endDay;
private int resYear;
private int resMonth;
private int resDay;
private Calendar start;
private Calendar end;
public String getCurrentDate()
{
      end=Calendar.getInstance();
      endYear=end.get(Calendar.YEAR);
      endMonth=end.get(Calendar.MONTH);
      endMonth++;
      endDay=end.get(Calendar.DAY_OF_MONTH);
      return endDay+":"+endMonth+":"+endYear;
}
public void setDateOfBirth(int sYear, int sMonth, int sDay)
{
 startYear=sYear;
 startMonth=sMonth;
 startDay=sDay;

}
public void calcualteYear()
{
    resYear=endYear-startYear/(365);

}

public void calcualteMonth()
{
    if(endMonth>=startMonth)
    {
         resMonth= endMonth-startMonth;
    }
    else
    {
        resMonth=endMonth-startMonth;
        resMonth=12+resMonth;
        resYear--;
    }

}
public void  calcualteDay()
{

    if(endDay>=startDay)
    {
         resDay= endDay-startDay;
    }
    else
    {
        resDay=endDay-startDay;
        resDay=30+resDay;
        if(resMonth==0)
        {
            resMonth=11;
            resYear--;
        }
        else
        {
            resMonth--;
        }

    }
}

public String getResult()
{
    return resDay+":"+resMonth+":"+resYear;
}
查看更多
聊天终结者
6楼-- · 2020-06-03 01:54

Here is a Java method called getAge which takes integers for year month and day and returns a String type which holds an integer that represents age in years.

private String getAge(int year, int month, int day){
    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--; 
    }

    Integer ageInt = new Integer(age);
    String ageS = ageInt.toString();

    return ageS;  
}
查看更多
ら.Afraid
7楼-- · 2020-06-03 01:54
static int calculateAge(int birthdayDay, int birthdayMonth, int birthdayYear)
{
    DateTime date = DateTime(birthdayYear, birthdayMonth, birthdayDay).toLocal();
    DateTime now = DateTime.now().toLocal();

    return now.difference(date).inDays ~/ 365.2425;
}
查看更多
登录 后发表回答