当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何从android出生日期算出一个人的确切年龄》经验,为你挑选了1个好方法。

与乔达图书馆:

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> samsad..:

与乔达图书馆:

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 ;

}

推荐阅读
夏晶阳--艺术
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有