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

时间:2017-01-10 06:58:42

标签: java android

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

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

请帮帮我...... !!!!!!

以下是我尝试过的代码。

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;

}

10 个答案:

答案 0 :(得分:6)

使用Joda Library:

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

没有图书馆:

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 ;

}

答案 1 :(得分:3)

calculate age的引用中,使用句点类如下:

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

希望它能解决你的问题。

答案 2 :(得分:3)

使用以下代码段来计算年龄:

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

    }
}

答案 3 :(得分:1)

试试这个......

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

答案 4 :(得分:1)

在这里,我将年龄计算为年/月/日,可以准确地解决您的问题。

  1. 输入来自日期选择器。

  2. 查看以下代码here

    #marker cluster
    corpus_chris_loc = [27.783889, -97.510556]
    
    harvey_avg_losses_map = folium.Map(location = corpus_chris_loc, zoom_start = 5)
    
    marker_cluster = MarkerCluster().add_to(harvey_avg_losses_map)
    
    #inside the loop add each marker to the cluster
    for row_index, row_values in harvey_losses.iterrows():
    
        loc = [row_values['lat'], row_values['lng']]
        pop = ("zip code: " + str(row_values["loss_location_zip"]) + "\nzip_avg: " + "$" + str(row_values['zip_avg'])) #show the zip and it's avg
        icon = folium.Icon(color='red')
        marker = folium.Marker(
            title = "Harvey: " + "$" + str(row_values['harvey_avg']),
            location = loc, 
            popup = pop,
            icon=icon) 
    
        marker.add_to(marker_cluster)
    
    
    #save an interactive HTML map by calling .save()
    
    harvey_avg_losses_map.save('../data/harveylossclustermap.html')
    
    harvey_avg_losses_map[map of hurricane harvey insurance claims][1]
    

答案 5 :(得分:0)

试试这个

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

here

找到解决方案 希望能帮到你!

答案 6 :(得分:0)

这将是从给定日期开始计算年龄的每种条件的合适方法-

Collection

在MainActivity中

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

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

答案 7 :(得分:0)

我知道这已经是一个老问题了,但是日期计算总是可以追溯到讨论中。

这是im实际用于获取两个日期之间确切年份的方法:

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

-编辑

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

但是在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";
}

答案 8 :(得分:0)

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

答案 9 :(得分:0)

使用JakeWharton库ThreeTenABP。由于它易于使用并提供了很棒的功能。

实施

首先,实现Age Model类:

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

第二,一些功能方面的东西:

此函数将验证日期,例如不大于今天的日期,但如果要更改最大范围,也可以在( currentDate )参数中传递日期。其次,它还将检查以下日期:2月30日,6月31日并返回null。等等……

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