Can we calculate an age in java without worrying about number of leap years between birth date and current date? Is there simple way to calculate it? …. The answer is yes. When we calculate somebody’s age manually, we do not think about number of leap year or number of days in each year. Same logic can be applies for calculating age programmatically.

Following is a code snippet for calculating the age. Please leave comment if it has helped you. Also please let me know if you feel this can be further optimized or this can be achieved by more simpler way...

Following is a code snippet for calculating the age. Please leave comment if it has helped you. Also please let me know if you feel this can be further optimized or this can be achieved by more simpler way...

int years = 0; int months = 0; int days = 0; //create calendar object for birth day Calendar birthDay = Calendar.getInstance(); birthDay.set(Calendar.YEAR, 2005); birthDay.set(Calendar.MONTH, Calendar.SEPTEMBER); birthDay.set(Calendar.DATE, 29); //create calendar object for current day long currentTime = System.currentTimeMillis(); Calendar currentDay = Calendar.getInstance(); currentDay.setTimeInMillis(currentTime); //Get difference between years years = currentDay.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR); int currMonth = currentDay.get(Calendar.MONTH)+1; int birthMonth = birthDay.get(Calendar.MONTH)+1; //Get difference between months months = currMonth - birthMonth; //if month difference is in negative then reduce years by one and calculate the number of months. if(months < 0) { years--; months = 12 - birthMonth + currMonth; if(currentDay.get(Calendar.DATE)<birthDay.get(Calendar.DATE)) months--; }else if(months == 0 && currentDay.get(Calendar.DATE) < birthDay.get(Calendar.DATE)){ years--; months = 11; } //Calculate the days if(currentDay.get(Calendar.DATE)>birthDay.get(Calendar.DATE)) days = currentDay.get(Calendar.DATE) - birthDay.get(Calendar.DATE); else if(currentDay.get(Calendar.DATE)<birthDay.get(Calendar.DATE)){ int today = currentDay.get(Calendar.DAY_OF_MONTH); currentDay.add(Calendar.MONTH, -1); days = currentDay.getActualMaximum(Calendar.DAY_OF_MONTH)-birthDay.get(Calendar.DAY_OF_MONTH)+today; }else{ days=0; if(months == 12){ years++; months = 0; } } System.out.println("The age is : "+years+" years, "+months+" months and "+days+" days" );

I have checked it with many dates and it is correct on every occasion.Good work.

ReplyDeleteThose guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.

ReplyDeletejava training in bangalore