I want to calculate age from a date of birth in Date
. I have tried with this code which seems to work fine, but is it the most convenient way?
LocalDate hoy = LocalDate.now();
LocalDate nacimiento = usuarioActivo.getFechaNacimiento().toInstant().
atZone(ZoneId.systemDefault()).toLocalDate();
long edad = ChronoUnit.YEARS.between(nacimiento, hoy);
The Java 8 API for Dates and Times is tremendous. I use it and it is my favourite. You can use JODA as @Alejandro Rangel Celis tells you, which is compatible with older versions of Java.
Java 8
The way you have it is valid, but not quite correct because you don't take the months into account. For this you can use the Period class :
Departure:
Check out Joda , it simplifies date and time calculations (Joda is also the basis for the new date/time apis standard in Java).
Java 8 has something very similar and is worth checking out.
Example
Here is a similar question on the English site.
I start to program java with NetBeans 11 and I just had this problem, I solved it in the following way: (I hope it works for you)