简体   繁体   中英

How to calculate age by days

I know that there are many ways that are already posted here but I couldn't find a way that finds a solution in the way I want.

public void CheckAge(int day, int month, int year) {
        LocalDate today = LocalDate.now();
        this.day = day;
        this.month = month;
        this.year = year;
        int month2 = today.getMonthValue();
        int day2 = today.getDayOfMonth();
        int year2 = today.getYear();
        int AnimalSum = year*365+day*month;
        int todaySum = ((year2*365)+(day2*(month2)));
        
          System.out.println("Years: "+(year2- year)+" Months: "+ (((todaySum-AnimalSum)/365)/12)+" Days: "+(((todaySum-AnimalSum)/365)));
           
    }

I couldn't calculate the days. Thanks.

You can use Duration .

LocalDateTime birthDay = LocalDateTime.of(1974,8, 10,0,0);
LocalDateTime now = LocalDateTime.now();
long days = Duration.between(birthDay, now).toDays();

prints

17263

What you need is a Period it lets you get difference between two dates.

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Period.html

java.time.Period

A Period in Java is a period of years, months and days. The Period class can calculate the period between two dates.

public void checkAge(int day, int month, int year) {
    LocalDate then = LocalDate.of(year, month, day);
    LocalDate today = LocalDate.now(ZoneId.systemDefault());
    Period age = Period.between(then, today);
    
    System.out.format("Years: %d Months: %d Days: %d%n", age.getYears(), age.getMonths(), age.getDays());
}

Let's try it out:

    checkAge(24, 11, 1994);

Output when run today:

Years: 26 Months: 11 Days: 21

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM