从出生日期计算年龄

编程入门 行业动态 更新时间:2024-10-28 04:17:59
本文介绍了从出生日期计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

从出生日期计算年龄

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

发布评论

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

>www.elefans.com

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