Calculate age in Years, Months, Days, Hours, Minutes, and Seconds

后端 未结 4 1501
臣服心动
臣服心动 2020-12-21 02:04

I need to take a birthday entered by the user (preferably in dd/mm//yyyy format) and find their age, based on todays date. Could someone explain to me the proce

4条回答
  •  太阳男子
    2020-12-21 02:34

    java.time

    Using the java.time framework built into Java 8 and later. Example is copy pasted directly from Tutorial (with small modifications).

    import java.time.Period
    import java.time.LocalDate
    import java.time.format.DateTimeFormatter
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");    
    LocalDate today = LocalDate.now();
    LocalDate birthday = LocalDate.parse("1/1/1960", formatter);
    
    
    Period p = Period.between(birthday, today);
    System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
                       " months and " + p.getDays() +
                       " days old.");
    

    The code produces output similar to the following:

    You are 53 years, 4 months and 29 days old.

    In my opinion it doesn't make sense to output hour, minutes and seconds because you probably won't have such precise data in your DB. That is why example uses LocalDate instead of LocalDateTime.

提交回复
热议问题