Using Calendar
you can easily get a 10 year old date and 20 year old date from the current date.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -10);
Date d1 = calendar.getTime();
calendar.add(Calendar.YEAR, -10);
Date d2 = calendar.getTime();
As you are using Java 8 you can also use LocalDate
LocalDate currentDate = LocalDate.now();
Date d1 = Date.from(currentDate.minusYears(10).atStartOfDay(ZoneId.systemDefault()).toInstant());
Date d2 = Date.from(currentDate.minusYears(20).atStartOfDay(ZoneId.systemDefault()).toInstant());
For comparing you can use the date.after()
and date.before()
methods as you said.
if(date.after(d1) && date.before(d2)){ //date is the Date instance that wants to be compared
////
}
The before()
and after()
methods are implemented in Calendar
and LocalDate
too. You can use those methods in those instances without converting into java.util.Date
instances.