码迷,mamicode.com
首页 > 其他好文 > 详细

【根据生日获取年龄】

时间:2018-01-19 11:29:13      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:catch   返回   post   turn   new   throw   settime   log   ati   

【根据生日获取年龄】

/**
* 根据生日获取年龄
* @param birthday
* @return
* @throws Exception
*/
private static int getAgeByBirth(Date birthday) throws Exception {
int age = 0;
try {
Calendar now = Calendar.getInstance();
now.setTime(new Date());// 当前时间
Calendar birth = Calendar.getInstance();
birth.setTime(birthday);
if (birth.after(now)) {//如果传入的时间,在当前时间的后面,返回0岁
age = 0;
} else {
age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
age += 1;
}
}
return age;
} catch (Exception e) {//兼容性更强,异常后返回数据
return 0;
}
}

【根据生日获取年龄】

标签:catch   返回   post   turn   new   throw   settime   log   ati   

原文地址:https://www.cnblogs.com/duanqiao123/p/8315321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!