How do I calculate someone's age in Java?

前端 未结 28 2320
渐次进展
渐次进展 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: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.
    }
    

提交回复
热议问题