检查日期是否超过10年且超过20年

And*_*897 24 java date java-8 java-time

我试图在Java 8中检查日期是否超过10年且超过20年.我使用Date.before()And Date.after()并且经过currentDate-10多年和currentDate-20岁月作为论据.

有人可以建议什么是最简单的方法来获取日期格式为10年和20年的日期格式,以传递给我before()after()方法?

dku*_*rni 34

您可以使用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
}
Run Code Online (Sandbox Code Playgroud)

  • 我冒昧地创建了一个单独的变量来解决@SpaceTrucker引发的问题.如果您愿意,请随意回滚.另请注意,此答案忽略了*time*和*time zone*的问题.我可能会首先使用`atStartOfDay`截断时间,时区处理将取决于具体的用例. (2认同)

Ram*_*h-X 20

使用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();
Run Code Online (Sandbox Code Playgroud)

在使用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());
Run Code Online (Sandbox Code Playgroud)

为了比较,你可以使用date.after()date.before()你说的方法.

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

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

  • 虽然这适用于java 8,但我建议使用新的日期和时间api. (8认同)