检查日期是否早于 10 年和新于 20 年

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

我正在尝试检查 Java 8 如果日期早于 10 年且晚于 20 年。我正在使用 Date.before()Date.after() 并传递 currentDate-10 年和 currentDate-20 年作为参数。

有人可以建议什么是最干净的方法来获取日期格式的 10 岁和 20 岁的日期以将其传递到我的 before()after() 方法中?

使用 Calendar 你可以很容易地从当前日期得到一个 10 年前的日期和 20 年前的日期。

Calendar calendar  = Calendar.getInstance();
calendar.add(Calendar.YEAR, -10);
Date d1 = calendar.getTime();
calendar.add(Calendar.YEAR, -10);
Date d2 = calendar.getTime();

当你使用 Java 8 你也可以使用 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());

如您所说,您可以使用 date.after()date.before() 方法进行比较。

    if(date.after(d1) && date.before(d2)){  //date is the Date instance that wants to be compared
        ////
    }

before()after() 方法也在 CalendarLocalDate 中实现。您可以在这些实例中使用这些方法,而无需转换为 java.util.Date 个实例。

您可以使用 java.time.LocalDate 来执行此操作。 示例:如果您需要检查 01/01/2005 是否在该持续时间之间,您可以使用

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
}

另一种可能性是获取要检查的日期和上限日期之间的年份。如果年数大于0且小于10,则表示要检查的日期早于10年且晚于20年。

此代码将确定区间 ]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");
    }
}