How do I calculate someone's age in Java?

前端 未结 28 2825
渐次进展
渐次进展 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:04

    /**
     * Compute from string date in the format of yyyy-MM-dd HH:mm:ss the age of a person.
     * @author Yaron Ronen
     * @date 04/06/2012  
     */
    private int computeAge(String sDate)
    {
        // Initial variables.
        Date dbDate = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      
    
        // Parse sDate.
        try
        {
            dbDate = (Date)dateFormat.parse(sDate);
        }
        catch(ParseException e)
        {
            Log.e("MyApplication","Can not compute age from date:"+sDate,e);
            return ILLEGAL_DATE; // Const = -2
        }
    
        // Compute age.
        long timeDiff = System.currentTimeMillis() - dbDate.getTime();      
        int age = (int)(timeDiff / MILLI_SECONDS_YEAR);  // MILLI_SECONDS_YEAR = 31558464000L;
    
        return age; 
    }
    

提交回复
热议问题