如何比较 Java 中的两个日期,然后将结果与另一个日期进行比较?

Vla*_*dik 2 java

菜鸟在这里!首先,我试图相互比较dateOnedateTwo相互比较,然后(> 0)取最近日期的那个并将其与cutOffDate.

如果是之后cutOffDate,则将其设置为FinalDate,否则设置cutOffDateFinalDate。我怎样才能做到这一点?

我不确定我在这里是否在正确的轨道上,我收到以下错误dateOne.compareTo(dateTwo)

String 类型中的 compareTo(String) 方法不适用于参数 (Date)

public DateServiceImpl process(final DateServiceImpl item) throws Exception {

    final Date dateOne = item.getDateOne();
    final Date dateTwo = item.getDateTwo();

    final BigDecimal amountOne= item.getAmountOne();
    final BigDecimal amountTwo= item.getAmountTwo();

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    String cutOffDate = "01/01/2020";

    Date cDate = sdf.parse(cutOffDate);
    if ((amountOne.compareTo(BigDecimal.ZERO) > 0) && (amountTwo.compareTo(BigDecimal.ZERO) > 0)){
        if (dateOne.compareTo(dateTwo) <= 0) {
             item.setFinalDate(cDate);
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ole*_*.V. 5

来自 java.time 和 Collections.max() 的 LocalDate

一定要使用 java.time,现代 Java 日期和时间 API,为您的日期工作。首先, java.time 允许一劳永逸地声明格式化程序:

private static final DateTimeFormatter DATE_FORMATTER
        = DateTimeFormatter.ofPattern("MM/dd/yyyy");
Run Code Online (Sandbox Code Playgroud)

据我所知,最终的日期应该是最新的dateOnedateTwo和截止日期。鉴于DateServiceImpl使用LocalDate代替Date,逻辑可以简化:

    LocalDate dateOne = item.getDateOne();
    LocalDate dateTwo = item.getDateTwo();

    String cutOffDate = "01/01/2020";

    LocalDate cDate = LocalDate.parse(cutOffDate, DATE_FORMATTER);

    LocalDate finalDate = Collections.max(Arrays.asList(dateOne, dateTwo, cDate));

    item.setFinalDate(finalDate);
Run Code Online (Sandbox Code Playgroud)

我省略了final声明和金额逻辑,因为它们与所提出的问题无关;你可以把它们放回去。

ALocalDate是没有时间的日期。我认为这就是您所需要的,请检查自己。

编辑:罗勒布尔克建议在评论中,如果使用Java 9或更高版本,你可能会喜欢List.of()Arrays.asList()

    LocalDate finalDate = Collections.max(List.of(dateOne, dateTwo, cDate));
Run Code Online (Sandbox Code Playgroud)

对于这还不够的情况,LocalDate还有方法isBeforeisAfter比较。

Collections.max() 也适用于 Date

如果您DateServiceImpl现在负担不起升级到 java.time,您可以以同样的方式Collections.max()在三个老式Date对象上使用。

Collections.max()也有一个重载版本,它Comparator作为它的第二个参数。由于两者LocalDateDate实施Comparable我们在这里不需要。

链接

  • 感谢您教我“Collections.max”。对于使用 Java 9 及更高版本的用户,请使用 [`List.of`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html #of(E,E,E)) 可能比 `Arrays.asList` 更容易阅读:`LocalDate FinalDate = Collections.max( List.of( dateOne , dateTwo , cDate ) );`。但无论哪种方式效果都相同。 (2认同)