How do I calculate someone's age in Java?

前端 未结 28 2300
渐次进展
渐次进展 2020-11-22 02:20

I want to return an age in years as an int in a Java method. What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)):



        
28条回答
  •  清酒与你
    2020-11-22 02:53

    I simply use the milliseconds in a year constant value to my advantage:

    Date now = new Date();
    long timeBetween = now.getTime() - age.getTime();
    double yearsBetween = timeBetween / 3.15576e+10;
    int age = (int) Math.floor(yearsBetween);
    

提交回复
热议问题