1 PackageGetage;2 ImportJava.text.SimpleDateFormat;3 ImportJava.util.Calendar;4 Importjava.util.Date;5 6 /**7 * Age accuracy based on user's birthday8 * Use the Calender object to get the current date object--Remove the date from the object9 * @authorAdministratorTen * One */ A Public classgetagebybirthday{ - Public Static intGetagebybirth (Date birthday) { - //Calendar: Calendars the /*from a Calendar object or a Date object*/ -Calendar cal =calendar.getinstance (); - /*Place the date of birth into the Bir object of the calendar type and convert the calendar and date types*/ -Calendar Bir =calendar.getinstance (); + bir.settime (birthday); - /*throws an exception if the birthday is greater than the current date: the date of birth cannot be greater than the current date*/ + if(Cal.before (birthday)) { A Throw NewIllegalArgumentException ("The birthday is before Now,it ' s unbelievable"); at } - /*Take out the current month day*/ - intYearnow =Cal.get (calendar.year); - intMonthnow =Cal.get (calendar.month); - intDaynow =Cal.get (calendar.day_of_month); - /*Remove Birth date*/ in intYearbirth =Bir.get (calendar.year); - intMonthbirth =Bir.get (calendar.month); to intDaybirth =Bir.get (calendar.day_of_month); + /*The approximate age is the current year minus the year of birth*/ - intAge = Yearnow-Yearbirth; the /*If the current month is small with the birth month, or the current month is equal to the birth month but the current day is less than the birthday, then age is reduced by one year*/ * if(Monthnow < Monthbirth | | (Monthnow = = Monthbirth && Daynow <Daybirth)) { $age--;Panax Notoginseng } - returnAge ; the } + /*Main Method Test*/ A Public Static voidMain (string[] args) { theSimpleDateFormat sft =NewSimpleDateFormat ("Yyyy-mm-dd"); +String Sftbirth = "1980-4-25"; -Date Date =NULL; $ Try{ $Date =Sft.parse (Sftbirth); -}Catch(Exception e) { - e.printstacktrace (); the } - intAge =Getagebybirthday.getagebybirth (date);WuyiSystem.out.print ("Age =" + ages + "Years")); the } -}
Java calculates age accurately based on birthday