How do I calculate someone's age in Java?

前端 未结 28 2363
渐次进展
渐次进展 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 03:01

    The fields birth and effect are both date fields:

    Calendar bir = Calendar.getInstance();
    bir.setTime(birth);
    int birthNm = bir.get(Calendar.DAY_OF_YEAR);
    int birthYear = bir.get(Calendar.YEAR);
    Calendar eff = Calendar.getInstance();
    eff.setTime(effect);
    

    This basically a modification of John O's solution without using depreciated methods. I spent a fair amount of time trying to get his code to work in in my code. Maybe this will save others that time.

提交回复
热议问题