2
Date currentDate=new Date();
DateFormat formatter=new SimpleDateFormat("dd-MM-yyyy");; 
Date date =(Date)formatter.parse(birthDate);     //birthDate is a String, in format dd-MM-yyyy
long diff = currentDate.getTime() - date.getTime();
long d=(1000*60*60*24*365);
long years = Math.round(diff / d);
age=(int) years;

The value of age is not returning right. What am I doing wrong?

Enter your birthdate: (in format dd-MM-yyyy)
25-07-1992
Current Date: Tue Apr 21 14:05:19 IST 2015
Birthday: Sat Jul 25 00:00:00 IST 1992

Output: Age is: 487

3 Answers3

7

If you write long d=(1000*60*60*24*365);, the result of 1000*60*60*24*365 will be calculated as int, while this is too large for int type. You should use 1000l*60*60*24*365 to calculate this.

locoyou
  • 1,697
  • 1
  • 15
  • 19
4

It's perhaps surprising to note that you don't need to know how many days or months there are in a year or how many days are in those months, likewise, you don't need to know about leap years, leap seconds, or any of that stuff using this simple, 100% accurate method:

public static int age(Date birthday, Date date) {
    DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    int d1 = Integer.parseInt(formatter.format(birthday));
    int d2 = Integer.parseInt(formatter.format(date));
    int age = (d2-d1)/10000;
    return age;
}
weston
  • 54,145
  • 21
  • 145
  • 203
  • I down voted your answer because it thought it was incorrect but I realized I was at fault and now I can't change my vote anymore. – Steve S. Jul 22 '16 at 11:47
  • @SteveS. thanks steve, I've just edited it, and so now you should be able to change the vote :) – weston Jul 22 '16 at 12:00
2

As well as issues mentioned in the comments above, this line causes a numeric overflow:

long d=(1000*60*60*24*365);

Remove that line, and use this instead; you'll get a roughly correct answer:

long years = Math.round(diff / 1000 / 60 / 60 / 24 / 365);
Steve Chaloner
  • 8,162
  • 1
  • 22
  • 38