从BirthDate计算年龄

编程入门 行业动态 更新时间:2024-10-27 14:34:08
本文介绍了从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计算年龄

本文发布于:2023-10-18 11:46:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504142.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:年龄   BirthDate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!