How do I calculate someone's age in Java?

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

    I appreciate all correct answers but this is the kotlin answer for the same question

    I hope would be helpful to kotlin developers

    fun calculateAge(birthDate: Date): Int {
            val now = Date()
            val timeBetween = now.getTime() - birthDate.getTime();
            val yearsBetween = timeBetween / 3.15576e+10;
            return Math.floor(yearsBetween).toInt()
        }
    
    0 讨论(0)
  • 2020-11-22 03:10

    Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you'll be learning a soon-to-be-standard API).

    EDIT: Java 8 has something very similar and is worth checking out.

    e.g.

    LocalDate birthdate = new LocalDate (1970, 1, 20);
    LocalDate now = new LocalDate();
    Years age = Years.yearsBetween(birthdate, now);
    

    which is as simple as you could want. The pre-Java 8 stuff is (as you've identified) somewhat unintuitive.

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

    This is an improved version of the one above... considering that you want age to be an 'int'. because sometimes you don't want to fill your program with a bunch of libraries.

    public int getAge(Date dateOfBirth) {
        int age = 0;
        Calendar born = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        if(dateOfBirth!= null) {
            now.setTime(new Date());
            born.setTime(dateOfBirth);  
            if(born.after(now)) {
                throw new IllegalArgumentException("Can't be born in the future");
            }
            age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);             
            if(now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR))  {
                age-=1;
            }
        }  
        return age;
    }
    
    0 讨论(0)
  • 2020-11-22 03:12
    import java.io.*;
    
    class AgeCalculator
    {
        public static void main(String args[])
        {
            InputStreamReader ins=new InputStreamReader(System.in);
            BufferedReader hey=new BufferedReader(ins);
    
            try
            {
                System.out.println("Please enter your name: ");
                String name=hey.readLine();
    
                System.out.println("Please enter your birth date: ");
                String date=hey.readLine();
    
                System.out.println("please enter your birth month:");
                String month=hey.readLine();
    
                System.out.println("please enter your birth year:");
                String year=hey.readLine();
    
                System.out.println("please enter current year:");
                String cYear=hey.readLine();
    
                int bDate = Integer.parseInt(date);
                int bMonth = Integer.parseInt(month);
                int bYear = Integer.parseInt(year);
                int ccYear=Integer.parseInt(cYear);
    
                int age;
    
                age = ccYear-bYear;
                int totalMonth=12;
                int yourMonth=totalMonth-bMonth;
    
                System.out.println(" Hi " + name + " your are " + age + " years " + yourMonth + " months old ");
            }
            catch(IOException err)
            {
                System.out.println("");
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:13
    Calendar now = Calendar.getInstance();
    Calendar dob = Calendar.getInstance();
    dob.setTime(...);
    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);
    int 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--;
      }
    }
    // age is now correct
    
    0 讨论(0)
  • 2020-11-22 03:14

    JDK 8 makes this easy and elegant:

    public class AgeCalculator {
    
        public static int calculateAge(LocalDate birthDate, LocalDate currentDate) {
            if ((birthDate != null) && (currentDate != null)) {
                return Period.between(birthDate, currentDate).getYears();
            } else {
                return 0;
            }
        }
    }
    

    A JUnit test to demonstrate its use:

    public class AgeCalculatorTest {
    
        @Test
        public void testCalculateAge_Success() {
            // setup
            LocalDate birthDate = LocalDate.of(1961, 5, 17);
            // exercise
            int actual = AgeCalculator.calculateAge(birthDate, LocalDate.of(2016, 7, 12));
            // assert
            Assert.assertEquals(55, actual);
        }
    }
    

    Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.

    0 讨论(0)
提交回复
热议问题