Java 如何从android中的出生日期计算一个人的确切年龄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41562905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:29:29  来源:igfitidea点击:

how to calculate the exact age of a person from date of birth in android

javaandroid

提问by suraj karnati

  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.

如果以上是条件,那么我想打印 26 作为当前年龄。第二个例子:birthdate :25-07-1991(ddmmyyyy)
CurrentDate : 10-01-2017如果以上是条件,那么我想打印 25 作为当前年龄。

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;

}

}

回答by Jagruttam Panchal

Try this

尝试这个

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

Found solution from here

这里找到解决方案

Hope will help you!

希望能帮到你!

回答by Rahul Sharma

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.

希望它能解决您的疑虑。

回答by samsad

With Joda Library :

使用 Joda 库:

LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);

Without Library :

没有图书馆:

public static int getAge(String date) {

int age = 0;
try {
    Date date1 = dateFormat.parse(date);
    Calendar now = Calendar.getInstance();
    Calendar dob = Calendar.getInstance();
    dob.setTime(date1);
    if (dob.after(now)) {
        throw new IllegalArgumentException("Can't be born in the future");
    }
    int year1 = now.get(Calendar.YEAR);
    int year2 = dob.get(Calendar.YEAR);
    age = year1 - year2;
    int month1 = now.get(Calendar.MONTH);
    int month2 = dob.get(Calendar.MONTH);
    if (month2 > month1) {
        age--;
    } else if (month1 == month2) {
        int day1 = now.get(Calendar.DAY_OF_MONTH);
        int day2 = dob.get(Calendar.DAY_OF_MONTH);
        if (day2 > day1) {
            age--;
        }
    }
} catch (ParseException e) {
    e.printStackTrace();
}
return age ;

}

}

回答by Sebastian

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

回答by Devram Kandhare

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

    }
}

回答by Gopal_Gupta

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.

我在日历中设置给定日期并将年、日和月发送到 getAge() 方法。您可以根据需要更改日期格式。

回答by ThiagoYou

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:

使用 JDK 8 更容易获得日期之间的年份差异:

(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:

但在 Android (JAVA) 中,这只适用于 API 26+,因此最好根据 SDK 版本使用这两种方法:

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

回答by Ashish Chaugule

Check this for android in Kotlin :

在 Kotlin 中为 android 检查这个:

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
    }

回答by Prathamesh Jadhav

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");
                }
            }
    
  1. 输入来自日期选择器。

  2. 看看这个代码在这里

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