Although many online based on the date of calculation of age, but some rough calculation of age, some will not protect the future date, so that the age of negative situation.
So, self-clothed, wrote the following tool class:
PackageCom.jglz.qing.age;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;Importjava.util.Date;/*** Created by Qing on 2017/3/28.*/ Public classAgeutils {//birthtimestring: "1994-11-14" according to the age of the month and day Public Static intgetagefrombirthtime (String birthtimestring) {//first intercept the year, month, and day in the stringString strs[] = Birthtimestring.trim (). Split ("-"); intSelectyear = Integer.parseint (strs[0]); intSelectmonth = Integer.parseint (strs[1]); intSelectday = Integer.parseint (strs[2]); //get the current time of year, month, dayCalendar cal =calendar.getinstance (); intYearnow =Cal.get (calendar.year); intMonthnow = Cal.get (calendar.month) + 1; intDaynow =Cal.get (calendar.date); //subtract birthday date from current month intYearminus = Yearnow-selectyear; intMonthminus = Monthnow-Selectmonth; intDayminus = Daynow-Selectday; intage = Yearminus;//approximate Assignment First if(Yearminus < 0) {//Choose the year of the futureAge = 0; } Else if(Yearminus = = 0) {//the same year, either 1, or 0 . if(Monthminus < 0) {//Choose the next month.Age = 0; } Else if(Monthminus = = 0) {//of the same month if(Dayminus < 0) {//Choose a date for the futureAge = 0; } Else if(Dayminus >= 0) { age= 1; } } Else if(Monthminus > 0) { age= 1; } } Else if(Yearminus > 0) { if(Monthminus < 0) {//Current Month > Birthday month}Else if(Monthminus = = 0) {//the same month, and then the age based on the date if(Dayminus < 0) { } Else if(Dayminus >= 0) { age= age + 1; } } Else if(Monthminus > 0) { age= age + 1; } } returnAge ; } //calculate age based on timestamp Public Static intGetagefrombirthtime (LongBirthtimelong) {Date Date=NewDate (Birthtimelong * 1000l); SimpleDateFormat format=NewSimpleDateFormat ("Yyyy-mm-dd"); String birthtimestring=Format.format (date); returnGetagefrombirthtime (birthtimestring); }}
Package Com.jglz.qing.age; Public class agetest { publicstaticvoid main (string[] args) { = "2016-3-28 "; int age = ageutils.getagefrombirthtime (dataofbirth); System.out.println ("Age:" + Age );} }
Today's date is 2017.3.38, so print "Age:2".
Java calculates age accurately based on date