Take the 2-minute tour ×

Possible Duplicate:
How do I calculate someone's age in Java?

I have two dates eg 19/03/1950 and 18/04/2011. how can i calculate the difference between them to get the person's age? do I have to keep multiplying to get the hours or seconds etc?

share|improve this question
look here: kodejava.org/examples/90.html –  Harry Joy Mar 4 '11 at 13:22
add comment

marked as duplicate by onof, Andrew White, justkt, Bala R, birryree Mar 4 '11 at 13:33


4 Answers

String date1 = "26/02/2011";
String date2 = "27/02/2011";
String format = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();

int diffDays =  (int) (diff / (24* 1000 * 60 * 60));
share|improve this answer
add comment

You use the classes Date and Duration:



You create Date-objects, then use Duration's methods addTo() and subtract()

share|improve this answer
Duration is only available in an XML context, as the package name suggests. –  Sean Patrick Floyd Mar 4 '11 at 13:32
add comment

The following code will give you difference between two dates:

import java.util.Date;
import java.util.GregorianCalendar;

public class DateDiff {
  public static void main(String[] av) {
    /** The date at the end of the last century */
    Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();

    /** Today's date */
    Date today = new Date();

    // Get msec from each, and subtract.
    long diff = today.getTime() - d1.getTime();

    System.out.println("The 21st century (up to " + today + ") is "
        + (diff / (1000 * 60 * 60 * 24)) + " days old.");
share|improve this answer
add comment

Why not use jodatime? It's much easier to calculate date and time in java.

You can get the year and use the method yearsBetween()

share|improve this answer
add comment
