How do I calculate someone's age in Java?
⚡TLDR
Punch the age out of Java using LocalDate and Period:
To get the age, call magic wand calculateAge
with a birthdate like LocalDate.of(1990, 5, 24)
.
Error and edge cases
Code error? Blame the hardware or the user. But mature programmers know handling exceptions is what makes a software resilient:
- Time zone: Remember to note the time difference when partying in different time zones. Account for the system's time zone when using
LocalDate.now()
. - Null inputs: What if Voldemort uses your code? He does not have a birthdate! A simple check at the start of the method will return
0
for such Dark-Lords. - Future birthdates: Is your user a time traveler? For birthdates in the future, an
IllegalArgumentException
should be thrown. No, you can't be born tomorrow!
Many roads lead to Rome
There are myriad ways to calculate age , but let's get you lost in fewer of them:
- ChronoUnit: Who needs a time machine when you have
ChronoUnit.YEARS.between(birthDate, LocalDate.now())
? It's another easy way to calculate the age. - Joda-Time: If you miss old timers, then
Joda-Time
is for you. However, cross-validate results, or you might land in an alternate timeline. - Calendar approach: If you want to go vintage, you can use
Calendar.getInstance()
. However, it's like riding a horse to work. Just throw it out!
Ironclad robustness
How strong is your age calculating code? Only testing will tell :
- Unit tests: Ensure your
calculateAge
method doesn't cheat at hide & seek. Test it with various date inputs, including the tricksy leap years. - Leap year handling: A year can sometimes pack an extra day! Ensure that your calculation includes leap years or face the wrath of February 29th.
- Exception handling: A good piece of code anticipates the storm. Brace your code for potential exceptions like DateTimeException on invalid dates.
Polishing your age calculator
Scrub until it shines:
- Months and days: When someone says they are 24, are they 24 years, 8 months, and 16 days old? For precise age, include months and days.
- Current date: While using
LocalDate.now()
, remember that the earth spins! If your method runs over midnight, the date might change causing discrepancies.
Linked
Was this article helpful?