本文介绍了从出生日期计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 DatePicker 对话框,当我当时选择日期时,我想计算它的工作年龄,但是当我当时选择当前年份的日期时,它显示 -1 年龄而不是 0 那么如何解决这个问题?请帮我解决它.我的代码如下:
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; } 推荐答案这里有一个名为 getAge 的 Java 方法,它接受年月日的整数,并返回一个 String 类型,该类型保存一个代表年龄的整数.
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; }更多推荐
从出生日期计算年龄
发布评论