How do I calculate someone's age in Java?

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

    The correct answer using JodaTime is:

    public int getAge() {
        Years years = Years.yearsBetween(new LocalDate(getBirthDate()), new LocalDate());
        return years.getYears();
    }
    

    You could even shorten it into one line if you like. I copied the idea from BrianAgnew's answer, but I believe this is more correct as you see from the comments there (and it answers the question exactly).

    0 讨论(0)
  • 2020-11-22 03:02

    What about this one?

    public Integer calculateAge(Date date) {
        if (date == null) {
            return null;
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date);
        Calendar cal2 = Calendar.getInstance();
        int i = 0;
        while (cal1.before(cal2)) {
            cal1.add(Calendar.YEAR, 1);
            i += 1;
        }
        return i;
    }
    
    0 讨论(0)
  • 2020-11-22 03:03
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.Period;
    
    public class AgeCalculator1 {
    
        public static void main(String args[]) {
            LocalDate start = LocalDate.of(1970, 2, 23);
            LocalDate end = LocalDate.now(ZoneId.systemDefault());
    
            Period p = Period.between(start, end);
            //The output of the program is :
            //45 years 6 months and 6 days.
            System.out.print(p.getYears() + " year" + (p.getYears() > 1 ? "s " : " ") );
            System.out.print(p.getMonths() + " month" + (p.getMonths() > 1 ? "s and " : " and ") );
            System.out.print(p.getDays() + " day" + (p.getDays() > 1 ? "s.\n" : ".\n") );
        }//method main ends here.
    }
    
    0 讨论(0)
  • 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; 
    }
    
    0 讨论(0)
  • 2020-11-22 03:05

    I use this piece of code for age calculation ,Hope this helps ..no libraries used

    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    
    public static int calculateAge(String date) {
    
        int age = 0;
        try {
            Date date1 = dateFormat.parse(date);
            Calendar now = Calendar.getInstance();
            Calendar dob = Calendar.getInstance();
            dob.setTime(date1);
            if (dob.after(now)) {
                throw new IllegalArgumentException("Can't be born in the future");
            }
            int year1 = now.get(Calendar.YEAR);
            int year2 = dob.get(Calendar.YEAR);
            age = year1 - year2;
            int month1 = now.get(Calendar.MONTH);
            int month2 = dob.get(Calendar.MONTH);
            if (month2 > month1) {
                age--;
            } else if (month1 == month2) {
                int day1 = now.get(Calendar.DAY_OF_MONTH);
                int day2 = dob.get(Calendar.DAY_OF_MONTH);
                if (day2 > day1) {
                    age--;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return age ;
    }
    
    0 讨论(0)
  • 2020-11-22 03:07

    If you are using GWT you will be limited to using java.util.Date, here is a method that takes the date as integers, but still uses java.util.Date:

    public int getAge(int year, int month, int day) {
        Date now = new Date();
        int nowMonth = now.getMonth()+1;
        int nowYear = now.getYear()+1900;
        int result = nowYear - year;
    
        if (month > nowMonth) {
            result--;
        }
        else if (month == nowMonth) {
            int nowDay = now.getDate();
    
            if (day > nowDay) {
                result--;
            }
        }
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题