Calculate the exact number of years between a birth date and today using java 8 stream api
The Java code you've provided,
FindBirthday, correctly calculates the age in years between a specified birth date and the current date using the java.time package introduced in Java 8. Here's an explanation of the code:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class FindBirthday {
public static void main(String[] args){
// Define the birthday as July 21, 1982
LocalDate birthDay = LocalDate.of(1982, 7, 21);
// Get the current date
LocalDate today = LocalDate.now();
// Calculate the difference in years between the birthday and today
// ChronoUnit.YEARS.between() directly gives the number of full years between two dates
System.out.println(ChronoUnit.YEARS.between(birthDay, today));
}
}
Explanation
import java.time.LocalDate;: This line imports theLocalDateclass, which represents a date without a time zone, keeping the year, month, and day of the month. It's ideal for storing dates like birthdays. Baeldung notes thatLocalDateis helpful because it represents just a date, compared to Java'sDateclass, which represents both a date and a time.import java.time.temporal.ChronoUnit;: This line imports theChronoUnitenum, which provides various standard units of time, such as years, months, days, hours, minutes, seconds, and so on. It is used here to define the unit of time for the calculation (years, in this case).public class FindBirthday { ... }: This defines a public class namedFindBirthdaythat contains themainmethod.public static void main(String[] args){ ... }: This is themainmethod, the entry point for the Java application.LocalDate birthDay = LocalDate.of(1982, 7, 21);: ALocalDateobject namedbirthDayis created and initialized to July 21, 1982. TheLocalDate.of()method allows you to construct aLocalDateby providing the year, month, and day.LocalDate today = LocalDate.now();: ALocalDateobject namedtodayis created and set to the current date (which is July 19, 2025, based on the context provided) using theLocalDate.now()method.System.out.println(ChronoUnit.YEARS.between(birthDay, today));: This line calculates the age in years and prints it to the console. WsCube Tech states thatChronoUnit.YEARS.between()calculates the difference between two dates.ChronoUnit.YEARS.between(birthDay, today): This method calculates the number of full years that have passed betweenbirthDayandtoday. This correctly handles cases where the birthday hasn't occurred yet in the current year. For example, if today were July 1, 2025, the age would still be calculated based on the completed years. WsCube Tech explains thatChronoUnit.YEARS.between()calculates the difference in years between two dates without needing to manually check for leap years or month differences.
Output
Given the
birthDay of July 21, 1982, and the today being July 19, 2025 (based on the context), the output will be:42