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?
Asked
Active
Viewed 9,230 times
5
-
1https://docs.oracle.com/javase/tutorial/datetime/iso/period.html – Michael Markidis May 20 '16 at 06:27
3 Answers
9
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

Community
- 1
- 1

darshgohel
- 382
- 2
- 13
2
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)");

Chong We Tan
- 233
- 5
- 15
1
Here is a wery way of doing it
long age = LocalDate.from(birthday)).until(LocalDate.now(), ChronoUnit.YEARS);

Sergii Bishyr
- 8,331
- 6
- 40
- 69