-2

I have an Problem with calculating an Age..

public long getAlter() {

    Date now = new Date();
    long yearInMillis = 365 * 24 * 60 * 60  * 1000;
    long alter =   (now.getTime() - buildYear.getTime()) /365/24/60/60/1000 ;

    return alter;
}
  • The buildYear is given: Year 22.05.2007.

--> (dd.mm.yyyy)

  1. I need a function to calculate the Year (not the Month or so), in this example here: 7 Years.
  2. I need a function to calculate the Days, in this example 2576 Days.

How can I define this?

Like this: http://www.topster.de/kalender/zeitrechner.php?styp=zeit&sdatum=22.05.2007&szeit=12%3A00%3A00&edatum=&ezeit=12%3A00%3A00&typ=jetzt&subDazu=%2B&jahredazu=0&tagedazu=0&zeitdazu=00%3A00%3A00

(already choosen)

@ALL: It's not an duplicate, because I will not work with Joda!

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • No, I will dont use Joda! – user3714925 Jun 10 '14 at 14:09
  • You're going to get a whole lot of rounding errors with `/365/24/60/60/1000` – awksp Jun 10 '14 at 14:12
  • @user3714925 Duplicate doesn't suggest only Joda. You can also use classes added in Java 8 or `Calendar` as shown in different answers in that question. BTW you are having problem with integer overflow in `365 * 24 * 60 * 60 * 1000`. To solve it use `long` as first argument of multiplying so rest of arguments will also be long like `365L * 24 * 60 * 60 * 1000`. Also you didn't specify if mechanism should include also time (hours, minutes). This detail is important since there will be no full day between `1.1.2001 12:00` and `2.1.2001 11:59` because you will lack one second. – Pshemo Jun 10 '14 at 14:24

1 Answers1

3

This link seems to have done something similar:

How do I calculate someone's age in Java?

In case the link ever breaks, here is what is said:

Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).

EDIT: Java 8 will have something very similar and will be worth checking out.

e.g.

LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);

which is as simple as you could want. The current Java stuff is (as you've identified) somewhat unintuitive.

Community
  • 1
  • 1
krodmannix
  • 845
  • 10
  • 30