calculate Age In Year - Java java.util

Java examples for java.util:Year

Description

calculate Age In Year

Demo Code


//package com.java2s;

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**//from  w ww  .  j  av a 2 s.c  o  m
     * 
     * @param dateOfBirth
     * 
     * @return the age in year as of today
     */
    public static int calculateAgeInYear(Date dateOfBirth) {

        Calendar dob = Calendar.getInstance();
        dob.setTime(dateOfBirth);
        Calendar today = Calendar.getInstance();

        int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

        if (today.get(Calendar.DAY_OF_YEAR) <= dob
                .get(Calendar.DAY_OF_YEAR)) {
            age--;
        }
        // Note: if we input the value which is less than one year from current date, the result is -1
        // we thus want to just return zero instead of negative value to indicate that the person is less than one year old.
        if (age <= 0) {
            age = 0;
        }

        return age;
    }
}

Related Tutorials