Java calculates age based on birthday

Source: Internet
Author: User

The age of the birthday calculation can be achieved by calendar. The simplest can be considered get (calendar.day_of_year) to simple correction of age, but encounter birthdays in leap years after February 29, or this is a leap year February 29 may appear after the calculation is not allowed, error one day. So it's good to be honest.
Based on the age of birthdays, judging the date, the calculation is more accurate than the simple year.
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) {
Monthnow==monthbirth
if (Dayofmonthnow < Dayofmonthbirth) {
age--;
} else {
Do nothing
}
} else {
Monthnow>monthbirth
age--;
}
} else {
Monthnow<monthbirth
Donothing
}

return age;
}

Java calculates age based on birthday

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.