How can I create a calculation to get the age of a person from two dates?

后端 未结 2 1716
情话喂你
情话喂你 2021-01-29 07:05

I am trying to make a method that will calculate the age of a person. I want the calculation to be done under the second public static int

2条回答
  •  天命终不由人
    2021-01-29 07:51

    Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.

    Instead, save yourself (alot) of time and use a dedicated library

    Java 8

    LocalDate start = LocalDate.of(1972, Month.MARCH, 8);
    LocalDate end = LocalDate.now();
    
    long years = ChronoUnit.YEARS.between(start, end);
    System.out.println(years);
    

    Which outputs 43

    JodaTime

    DateTime startDate = new DateTime(1972, DateTimeConstants.MARCH, 8, 0, 0);
    DateTime endDate = new DateTime();
    
    Years y = Years.yearsBetween(startDate, endDate);
    int years = y.getYears();
    System.out.println(years );
    

    Which outputs 43

    You can even use a Period to gain more granuarlity...

        Period period = new Period(startDate, endDate);
        PeriodFormatter hms = new PeriodFormatterBuilder()
                        .printZeroAlways()
                        .appendYears()
                        .appendSeparator(" years, ")
                        .appendMonths()
                        .appendSeparator(" months, ")
                        .appendDays()
                        .appendLiteral(" days")
                        .toFormatter();
        String result = hms.print(period);
        System.out.println(result);
    

    Which prints 43 years, 1 months, 5 days

提交回复
热议问题