问题:您如何处理这些用例?
- 您使用静态辅助方法吗?
- 您是否使用详细的等号,后跟 isAfter/isBefore?
- 您是否使用否定的相反条件?
- 您使用第 3 方库助手吗?
在日常业务中,我经常需要检查日期 a <= 日期 b 或日期 a >= 日期 b。
互联网经常建议使用 isBefore/isAfter 方法的否定版本。
在实践中我发现我
- 几乎永远不会在第一次尝试时就正确地进行这些否定比较(它们应该直观且简单)。
- 阅读代码时很难理解业务逻辑
我想我的一部分仍然希望我只是忽略了 API 中的相应方法(拜托!)。
/**
* @return true if candidate >= reference </br>
* or in other words: <code>candidate.equals(reference) || candidate.isAfter(reference)</code> </br>
* or in other words: <code>!candidate.isBefore(reference) </br>
* or in other words: <code>candidate.compareTo(reference) >= 0
*/
public static boolean isEqualOrAfter(LocalDate candidate, LocalDate reference)
{
return !candidate.isBefore(reference);
}
/**
* @return true if candidate <= reference </br>
* or in other words: <code>candidate.equals(reference) || candidate.isBefore(reference)</code> </br>
* or in other words: <code>!candidate.isAfter(reference) </br>
* or in other words: <code>candidate.compareTo(reference) <= 0
*/
public static boolean isEqualOrBefore(LocalDate candidate, LocalDate reference)
{
return !candidate.isAfter(reference);
}
编辑:按照 Andreas 的建议,我添加了带有 compareTo
方法的版本,我希望我得到了正确的结果(无需测试)。
编辑2:示例:
// Manager says: "Show me everything from 3 days ago or later" or "show me everything that's at most 3 days old"
for(Item item : items) {
// negation idiom
if(!item.getDate().isBefore(LocalDate.now().minusDays(3))) {
// show
}
// compareTo idiom
if(item.getDate().compareTo(LocalDate.now().minusDays(3)) >= 0) {
// show
}
// desired
if(item.getDate().isEqualOrAfter(LocalDate.now().minusDays(3))) {
// show
}
}
最佳答案
你寻求的方法是不必要的。这就是你要做的:
isEqualOrBefore == !isAfter
isEqualOrAfter == !isBefore
关于java - LocalDate:缺少方法 isEqualOrBefore 和 isEqualOrAfter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43932309/