How can I create a calculation to get the age of a person from two dates?

后端 未结 2 1670
情话喂你
情话喂你 2021-01-29 07:05

I am trying to make a method that will calculate the age of a person. I want the calculation to be done under the second public static int

2条回答
  •  有刺的猬
    2021-01-29 07:57

    What is SimpleDate ? Anyway here something to get you started

     import java.util.GregorianCalendar;
     import java.util.Calendar;
    
     public class CalcAge {
    
       public static void main(String [] args) {
         // remember ... months are 0-based : jan=0 feb=1 ...
         System.out.println
           ("1962-11-11 : " + age(1962,10,11));
         System.out.println
           ("1999-12-03 : " + age(1999,11,3));
       }
    
       private static int age(int y, int m, int d) {
         Calendar cal = new GregorianCalendar(y, m, d);
         Calendar now = new GregorianCalendar();
         int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
         if((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
           || (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
           && cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
         {
            res--;
         }
         return res;
       }
    } 
    

提交回复
热议问题