Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LocalDate check if 18 years old and above

Tags:

java

date

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?

like image 717
Chong We Tan Avatar asked May 20 '16 06:05

Chong We Tan


2 Answers

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

like image 133
darshgohel Avatar answered Sep 29 '22 06:09

darshgohel


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)");
like image 40
Chong We Tan Avatar answered Sep 29 '22 07:09

Chong We Tan