I have 2 localdate, one is birthdate and one is date today. What is the fastest way to compare them and check if the age is 18 years old and above? Do I need to convert this to string and split them then compare them 1 by 1? Or is there another way of comparing this?
The java.time framework built into Java 8 and later has classes with lots of methods to solve the issue. The best one is finding Period. The exact code will be,
period = Period.between(start, end);
Here the start
will be your birthday such as LocalDate.of( 1955 , 1 , 2 )
and end
will be today: LocalDate.now()
.
After that you can get period.getYears()
which returns an int
value. Its easy to check condition that you want.
See Tutorial.
Reference: Java 8: Calculate difference between two LocalDateTime, LocalDate
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
" months, and " + p.getDays() +
" days old. (" + p2 + " days total)");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With