菜鸟在这里!首先,我试图相互比较dateOne和dateTwo相互比较,然后(> 0)取最近日期的那个并将其与cutOffDate.
如果是之后cutOffDate,则将其设置为FinalDate,否则设置cutOffDate为FinalDate。我怎样才能做到这一点?
我不确定我在这里是否在正确的轨道上,我收到以下错误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)
一定要使用 java.time,现代 Java 日期和时间 API,为您的日期工作。首先, java.time 允许一劳永逸地声明格式化程序:
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("MM/dd/yyyy");
Run Code Online (Sandbox Code Playgroud)
据我所知,最终的日期应该是最新的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);
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还有方法isBefore和isAfter比较。
如果您DateServiceImpl现在负担不起升级到 java.time,您可以以同样的方式Collections.max()在三个老式Date对象上使用。
Collections.max()也有一个重载版本,它Comparator作为它的第二个参数。由于两者LocalDate和Date实施Comparable我们在这里不需要。
Collections.max()