在3个日期之间找到最早的日期 [英] Find the earliest date among 3 dates
本文介绍了在3个日期之间找到最早的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
没有找到空的检查,但是通过一些重构,您可以使其无痛。
创建一个安全比较两个日期的方法:
/ **
*安全地比较两个日期,null被认为比$更早
* @返回最早的两个
* /
public static日期最少(日期a,日期b){
返回一个== null? b:(b == null?a:(a.before(b)?a:b));
}
然后结合调用:
Date earliest = least(least(a,b),c);
其实,你可以使这个通用的方法任何可比较
:
public static< T extends Comparable< T> > T最小(T a,T b){
返回一个== null? b:(b == null?a:(a.compareTo(b)< 0?a:b));
}
I have three dates in Java: a, b, c. Any or all of these dates may be null. What's the most efficient way of determining the earliest date among a,b,c, without having a massive if-else block?
解决方案
There's no getting around null checking, but with some refactoring you can make it painless.
Create a method that safely compares two dates:
/**
* Safely compare two dates, null being considered "greater" than a Date
* @return the earliest of the two
*/
public static Date least(Date a, Date b) {
return a == null ? b : (b == null ? a : (a.before(b) ? a : b));
}
then combine calls to that:
Date earliest = least(least(a, b), c);
Actually, you can make this a generic method for any Comparable
:
public static <T extends Comparable<T>> T least(T a, T b) {
return a == null ? b : (b == null ? a : (a.compareTo(b) < 0 ? a : b));
}
这篇关于在3个日期之间找到最早的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文