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

根据出生日期Date 计算年龄

时间:2015-06-10 19:33:41      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:时间   计算年龄   java年龄   date年龄   

根据出生日期计算年龄

public class DateGetAge
{
    public static int getAge(Date birthDay) throws Exception
    {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay))
        {
            throw new IllegalArgumentException(
                                               "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth)
        {
            if (monthNow == monthBirth)
            {
                if (dayOfMonthNow < dayOfMonthBirth)
                    age--;
            }
            else
            {
                age--;
            }
        }
        return age;
    }
}


根据出生日期Date 计算年龄

标签:时间   计算年龄   java年龄   date年龄   

原文地址:http://blog.csdn.net/csdnadcode/article/details/46444377

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