Check if date is older than 10 years and newer than 20 years

22,920

Solution 1

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.

Solution 2

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
}

Solution 3

Another possibility is to get the year count between the date to check and the upper date. If the number of year is greater than 0 and less than 10, it means the date to check is older than 10 years and newer than 20 years.

This code will determine any date in the interval ]now - 20 years ; now - 10 years[:

public static void main(String[] args) {
    LocalDate dateToCheck = LocalDate.now().minusYears(20).plusDays(1);

    LocalDate upperYear = LocalDate.now().minusYears(10);
    long yearCount = ChronoUnit.YEARS.between(dateToCheck, upperYear);
    if (yearCount > 0 && yearCount < 10) {
        System.out.println("date is older than 10 years and newer than 20 years");
    }
}
Share:
22,920
Andy897
Author by

Andy897

Updated on March 15, 2020

Comments

  • Andy897
    Andy897 over 4 years

    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?