First of all, the use of classes like java.util.Date
and java.util.Calendar
should be avoided, being alternative library classes Joda-Time or classes such as LocalDate
and LocalDateTime
, in addition to the rest of the datetime API java.time
present from Java 8.
Using the Java 8 API mentioned above, we can use the Period
to calculate the time interval between two dates, including the number of years. Thus, a possible implementation of a routine would be as follows:
public static int idade(final LocalDate aniversario) {
final LocalDate dataAtual = LocalDate.now();
final Period periodo = Period.between(aniversario, dataAtual);
return periodo.getYears();
}
The date is of type LocalDate
, object that contains only date, does not contain time and does not display the time zone problems of class java.util.Date
.
The Period#between
method calculates the period between the anniversary date and the current date created with LocalDate#now
.
Finally, the routine returns the number of years in the period.
After understanding how the method works, we could abbreviate it without the auxiliary variables as follows:
public static int idade(final LocalDate aniversario) {
return Period.between(aniversario, LocalDate.now()).getYears();
}
If, for some reason, the program needs to use different variables for day, month and year, just apply LocalDate.of
to create a date from the values and reuse the above routine:
public static int idade(final int dia, final int mes, final int ano) {
return idade(LocalDate.of(ano, mes, dia));
}
If, for another reason, the program needs to use dates of type java.util.Date
, we can perform the conversion to type LocalDate
and, once again, reuse the above routine:
public static int idade(final Date dataAniversario) {
return idade(LocalDateTime.ofInstant(dataAniversario.toInstant(), ZoneOffset.UTC).toLocalDate());
}
I again remember that insisting on java.util.Date
, java.util.Calendar
, and associated classes, such as SimpleDateFormat
and DateFormat
, often lead to problems in handling and calculating dates due to time zone problems. This causes the birthdays to have the incorrect value in periods affected by daylight saving time for at least one hour. other more serious problems by adding up and subtracting time.