Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+13 votes

To find the age in years and days I used LocalDate objects and used the DAYS.between(birthDate, deathDate); method by importing java.time.temporal.ChronoUnit.DAYS; and getting the total number of days between the two dates. I then took those total number of days and divided by 365 to get the years and mod by 365 to get the days. However it is a always a few days off due to leap years being 366 days. Did anyone find a way to get around this problem?

asked in CSC490_Spring2019 by (1 point)

3 Answers

+2 votes

I used the LocalDate class as well. I think I have a working solution. First I find the number of years between the two dates using the birthDate.until(deathDate, ChronoUnity.YEARS); Then, I add the number of years to the original birthDate. Then I find the difference in days between the new date and the deathDate. Here is a snipet of my code (where birthDate and deathDate are LocalDate objects:

long ageInYears = birthDate.until(deathDate, ChronoUnit.YEARS);
birthDate = birthDate.plusYears(ageInYears);
long leftoverDays = birthDate.until(deathDate, ChronoUnit.DAYS);

Note: my code checks to ensure the birthDate is before the deathDate, not sure if that matters. I think it would just make the age negative.

answered by (1 point)
+1 vote

You can easily find the difference between the two dates using LocalDate and Period. You don't really have to worry about leap years or anything because it has been handled already by LocalDate and Period. Here is my code if you want to take a look:

LocalDate birthDate = textToDate(birthdayEditText);
LocalDate diedDate = textToDate(diedEditText);
Period diff = birthDate.until(diedDate);

Then you can call diff.getYears() etc. to get what you want.

I hope this is helpful :)

answered by (1 point)
0 votes

I've had that problem too, i use the Calendar object to solve the problem.
The Calendar object do the leap year calculation for you

answered by (1 point)
...