I am trying to check in Java 8 if a date is older than 10 years and newer than 20 years. I am using Date.before()
And Date.after()
and passing currentDate-10
years and currentDate-20
years as arguments.
Can someone please suggest what will the cleanest way to get a date which is 10 year old and 20 years old in Date format to pass it in my before()
and after()
methods?
You can use java.time.LocalDate to do this. Example: If you need to check if 01/01/2005 is between that duration, you can use
LocalDate date = LocalDate.of(2005, 1, 1); // Assign date to check
LocalDate today = LocalDate.now();
if (date.isBefore(today.minusYears(10)) && date.isAfter(today.minusYears(20))) {
//Do Something
}