本文介绍了从BirthDate计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有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; }推荐答案
这是一个Java方法,称为getAge,它获取年份月份和日期的整数,并返回一个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; }更多推荐
从BirthDate计算年龄
发布评论