4

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?

Community
  • 1
  • 1
124697
  • 22,097
  • 68
  • 188
  • 315
  • look here: http://www.kodejava.org/examples/90.html – Harry Joy Mar 04 '11 at 13:22
  • Problem with with example at Kodejava.org is that if you wind a Gregorian calendar back some number of days and cross one DST boundry (particular if you cross "Spring Forward") then you're number of days backward calculation comes up one day short. – Stephen M -on strike- Jun 13 '14 at 19:23

4 Answers4

5
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));
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • This looks good, but it will not work for if stat date in in winter time and end date is in summer time, because you will be missing one hour and as you are using INT the result is rounded down. You need to use int diffDays = Math.round((float)diff / (24* 1000 * 60 * 60)); – Pavel Jiri Strnad Mar 09 '15 at 17:02
1

You use the classes Date and Duration:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Date.html

http://download.oracle.com/javase/1.5.0/docs/api/javax/xml/datatype/Duration.html

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

Community
  • 1
  • 1
Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
1

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.");
  }
}
Umesh K
  • 13,436
  • 25
  • 87
  • 129
1

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()

Fredrik
  • 61
  • 1
  • 5