gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:45:55 24 4
gpt4 key购买 nike

这里是菜鸟!首先,我试图比较 dateOnedateTwo 彼此,然后哪个具有最近的日期 (> 0)将其与 cutOffDate 进行比较。

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

我不确定我是否走在正确的轨道上,dateOne.compareTo(dateTwo) 出现以下错误:

The method compareTo(String) in the type String is not applicable for the arguments (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;
}
}

最佳答案

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

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

private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("MM/dd/yyyy");

我知道最后的日期应该是 dateOne 中最晚的日期。 , dateTwo和截止日期。鉴于 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);

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

一个 LocalDate是没有时间的日期。我认为这是您需要的,请检查自己。

编辑:正如 Basil Bourque 在评论中建议的那样,如果使用 Java 9 或更高版本,您可能会更喜欢 List.of()超过 Arrays.asList() :

    LocalDate finalDate = Collections.max(List.of(dateOne, dateTwo, cDate));

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

Collections.max() 也适用于 Date

如果您负担不起升级 DateServiceImpl刚才到java.time,你可以用Collections.max()关于三个老式Date对象以同样的方式。

Collections.max()还有一个重载版本,它需要 Comparator作为它的第二个论点。由于LocalDateDate实现Comparable我们这里不需要。

链接

关于java - 如何比较 Java 中的两个日期,然后将结果与另一个日期进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62440104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com