web-dev-qa-db-ja.com

BirthDateから年齢を計算する

DatePickerダイアログがあり、その時点で日付を選択すると機能しますが、現在の年の日付を選択すると0ではなく-1の年齢が表示されますが、これを解決するにはどうすればよいですか?解決してください。私のコードは以下の通りです:

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

ここに、getAgeと呼ばれるJavaメソッドがあります。このメソッドは、年月日を整数として、年単位の年齢を表す整数を保持するString型を返します。

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;  
}
31
Riyaz Parasara
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;
}
3
      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());
}

その後、1つのクラスを作成します

 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;
}
2
Nagini Kandula
 private boolean getAge(int year, int month, int day) {
    try {
        Calendar dob = Calendar.getInstance();
        Calendar today = Calendar.getInstance();
        dob.set(year, month, day);
        int monthToday = today.get(Calendar.MONTH) + 1;
        int monthDOB = dob.get(Calendar.MONTH)+1;
        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
        if (age > 18) {
            return true;
        } else if (age == 18) {
            if (monthDOB > monthToday) {
                return true;
            } else if (monthDOB == monthToday) {
                int todayDate = today.get(Calendar.DAY_OF_MONTH);
                int dobDate = dob.get(Calendar.DAY_OF_MONTH);
                if (dobDate <= todayDate) { // should be less then
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
2
shubham

以下は、Dateオブジェクトに対応する年齢を返すDateクラスのKotlin拡張です。

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

すべてのAndroidバージョンに対応しています。「1970」とは何かを疑問に思うなら、それはUnixエポックです。1970年1月1日のタイムスタンプは0です。

2
Rostan
public static String calculateAge(String strDate) {

    int years = 0;
    int months = 0;
    int days = 0;

    try {
        long timeInMillis = Long.parseLong(strDate);
        Date birthDate = new Date(timeInMillis);


        //create calendar object for birth day
        Calendar birthDay = Calendar.getInstance();
        birthDay.setTimeInMillis(birthDate.getTime());
        //create calendar object for current day
        long currentTime = System.currentTimeMillis();
        Calendar now = Calendar.getInstance();
        now.setTimeInMillis(currentTime);
        //Get difference between years
        years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
        int currMonth = now.get(Calendar.MONTH) + 1;
        int birthMonth = birthDay.get(Calendar.MONTH) + 1;

        //Get difference between months
        months = currMonth - birthMonth;


        //if month difference is in negative then reduce years by one and calculate the number of months.
        if (months < 0) {
            years--;
            months = 12 - birthMonth + currMonth;
            if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
                months--;
        } else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
            years--;
            months = 11;
        }
        //Calculate the days
        if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
            days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
        else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE)) {
            int today = now.get(Calendar.DAY_OF_MONTH);
            now.add(Calendar.MONTH, -1);
            days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
        } else {
            days = 0;
            if (months == 12) {
                years++;
                months = 0;
            }
        }
        //adarsh
        if (currMonth > birthMonth) {
            if (birthDay.get(Calendar.DATE) > now.get(Calendar.DATE)) {
                months = months - 1;
            }
        }//---------------------------------

    } catch (Exception e) {
        e.printStackTrace();
    }
    //Create new Age object
    return years + " Y " + months + " M " + days + " days";
}
1
adarsh
public String getAge(int year, int month, int day) {
        Calendar dob = Calendar.getInstance();
        Calendar today = Calendar.getInstance();

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

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

        return ageS;
    }
1
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;
}
1
Ido

これが、ソースコードに実装する方法です。テストしました。それが有用であることを願っています:

public static int getAge(String dateTime, String currentFormat) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(currentFormat);

    try {
        Date date = dateFormat.parse(dateTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

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


        Date currentDate = new Date();
        Calendar currentCalendar = Calendar.getInstance();
        currentCalendar.setTime(currentDate);

        int currentYear = currentCalendar.get(Calendar.YEAR);
        int currentMonth = currentCalendar.get(Calendar.MONTH);
        int currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH);

        int deltaYear = currentYear - year;
        int deltaMonth = currentMonth - month;
        int deltaDay = currentDay - day;

        if (deltaYear > 0) {
            if (deltaMonth < 0) {
                deltaYear --;
            } else if (deltaDay < 0){
                deltaYear --;
            }

            return deltaYear;
        }
    } catch (Java.text.ParseException e) {
        e.printStackTrace();
    }

    return 0;
}
0
Chi Minh Trinh
public int getAge(int year, int month, int day) {
    final Calendar birthDay = Calendar.getInstance();
    birthDay.set(year, month, day);
    final Calendar current = Calendar.getInstance();
    if (current.getTimeInMillis() < birthDay.getTimeInMillis())
        throw new IllegalArgumentException("age < 0");
    int age = current.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
    if (birthDay.get(Calendar.MONTH) > current.get(Calendar.MONTH) ||
            (birthDay.get(Calendar.MONTH) == current.get(Calendar.MONTH) &&
                    birthDay.get(Calendar.DATE) > current.get(Calendar.DATE)))
        age--;
    return age;
}
0
Joshua
String getAgeInOther(int year, int month, int day) {
    Calendar today = Calendar.getInstance();
    Calendar birth = Calendar.getInstance();
    birth.set(year, month, day);
    Calendar temp = Calendar.getInstance();
    temp.set(year, month, day);
    int totalDays = 0;

    int intMonth=0,intDays=0;

    for (int iYear = birth.get(Calendar.YEAR); iYear <= today.get(Calendar.YEAR); iYear++) {
        if (iYear == today.get(Calendar.YEAR) && iYear == birth.get(Calendar.YEAR)) {

            for (int iMonth = birth.get(Calendar.MONTH); iMonth <= today.get(Calendar.MONTH); iMonth++) {
                temp.set(iYear, iMonth, 1);
                if ((iMonth == today.get(Calendar.MONTH)) && (iMonth == birth.get(Calendar.MONTH))) {

                    totalDays += today.get(Calendar.DAY_OF_MONTH) - birth.get(Calendar.DAY_OF_MONTH);

                } else if ((iMonth != today.get(Calendar.MONTH)) && (iMonth != birth.get(Calendar.MONTH))) {

                    totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
                    intMonth++;

                }else  if ((iMonth == birth.get(Calendar.MONTH))) {

                    totalDays +=( birth.getActualMaximum(Calendar.DAY_OF_MONTH)- birth.get(Calendar.DAY_OF_MONTH));

                } else  if ((iMonth == today.get(Calendar.MONTH))){

                    totalDays += today.get(Calendar.DAY_OF_MONTH);



                    if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
                    {
                        intMonth++;
                        intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
                    }else {
                        temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
                        intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
                    }


                }


            }

        } else if ((iYear != today.get(Calendar.YEAR)) && (iYear != birth.get(Calendar.YEAR))) {



            for (int iMonth = 0; iMonth < 12; iMonth++) {
                temp.set(iYear, iMonth, 1);
                totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
                intMonth++;
            }


        } else if (((iYear) == birth.get(Calendar.YEAR))) {

            for (int iMonth = birth.get(Calendar.MONTH); iMonth < 12; iMonth++) {
                temp.set(iYear, iMonth, 1);
                if ((iMonth == birth.get(Calendar.MONTH))) {

                    totalDays += (birth.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH));

                } else {
                    intMonth++;
                    totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
                }
            }


        } else if (iYear == today.get(Calendar.YEAR)) {
            for (int iMonth = 0; iMonth <= today.get(Calendar.MONTH); iMonth++) {

                temp.set(iYear, iMonth, 1);
                if ((iMonth == today.get(Calendar.MONTH))) {

                    totalDays += today.get(Calendar.DAY_OF_MONTH);

                    if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
                    {
                        intMonth++;
                        intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
                    }else {
                        temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
                        intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
                    }

                } else {
                    intMonth++;
                    totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
                }
            }
        }
    }

    int  ageYear=intMonth/12;
    int  ageMonth=intMonth%12;
    int ageDays=intDays;
    //TODO if you want age in YEAR:MONTH:DAY REMOVE COMMENTS
   //TODO  return ageYear+":"+ageMonth+":"+ageDays;  
    return ""+totalDays;//todo TOTAL AGE IN DAYS

}
0

kotlin言語の場合:

import Java.util.Calendar


fun main(args: Array<String>) {


print(getAge(yyyy,mm,dd))

}

 fun getAge(year: Int, month: Int, day: Int): String {
    val dob = Calendar.getInstance()
    val today = Calendar.getInstance()

    dob.set(year, month, day)

    var age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR)

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

    val ageInt = age + 1

    return ageInt.toString()
}
0
Youn Tivoli