Using Java Calendar object find difference between dates:

In this method birthdate is taken in discrete inputs as year, month and date. You can modify the input birthday according to your needs.

Both number of years and number of months difference calculated. This can be extended to find number of days too….

public static void calculateAge(){
        
        int year = 1987;
        int month = 8;
        month = month - 1; // In Calendar object month starts from 0.
        int date = 16;	
        
        // First prepare today calendar object
        Calendar today = Calendar.getInstance();
        today.setTimeInMillis(System.currentTimeMillis());
        
        // Birthday calendar object
        Calendar birthDay = Calendar.getInstance();
        birthDay.set(year, month, date);
        
        // Get diff between years
        int ageYears = today.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
        
        // Get diff between months
        int ageMonths = 0;
        if(today.get(Calendar.MONTH) < birthDay.get(Calendar.MONTH)){
            ageMonths = 12 - (birthDay.get(Calendar.MONTH) - today.get(Calendar.MONTH));
            ageYears = ageYears - 1; // Adjust the years if the current month is behind the birth date month
        }else{
            ageMonths =  today.get(Calendar.MONTH) - birthDay.get(Calendar.MONTH);
        }
        
        System.out.println("Your Age is: "+ ageYears + " years and "+ageMonths + " months");
    }

 Output will be:

Your Age is: 30 years and 9 months

 
For further reading refer Java Programming Category posts.

Share this post

Java calculate difference between dates to find age
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *