-2

birthDate's type is java.util.Date . What is the best way to calculate the current age? I want a java.util.Date variable storing TODAY - birthDate.

David
  • 45
  • 6
  • 5
    Have you tried anything yet? – Konstantin Yovkov Mar 24 '16 at 14:28
  • What have you tried? Have you looked at how to obtain a date object with the current date? If you were not using a computer, what is the algorithm you would use? – KevinO Mar 24 '16 at 14:29
  • A `java.util.Date` represents a moment on the timeline. So by definition it cannot represent a span of elapsed time. So your request is impossible. Instead, look at the java.time framework, in particular the [`Period`](http://docs.oracle.com/javase/8/docs/api/java/time/Period.html) class. – Basil Bourque Mar 24 '16 at 19:53

1 Answers1

0

That depends on what do you mean by current age.

If you mean the precise astronomical meaning, use

DateTime startDate = new DateTime(2000, 1, 19, 5, 14, 0, 0);
DateTime endDate = new DateTime();
Days d = Days.daysBetween(startDate, endDate);

If you need the common sense difference, based on both dates given in whole days:

long thisDay = (new Date()).getTime() / (1000 * 60 * 60 * 24);

DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
Date birthDate = formatter.parse("11-June-07");

long birthdayInDays = birthDate.getTime() / (1000 * 60 * 60 * 24);
long dayDiff = thisDay - birthdayInDays;
Gangnus
  • 24,044
  • 16
  • 90
  • 149
  • tnx, but how can I go from this (`dayDiff`, or `d`), to a variable of type Date? – David Mar 24 '16 at 15:01
  • Take a look at this post: http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java – JYA Mar 24 '16 at 15:38
  • @David, difference of dates is NOT a date itself. A date, for example, has leap years. Difference of dates hasn't it. – Gangnus Mar 24 '16 at 16:03