乔达时间:DateTimeComparator。 Java 8 Time Api有什么相似之处?
随着乔达时间,你可以做一个非常酷的事情,例如:
package temp;
import org.joda.time.DateTime;
import org.joda.time.DateTimeComparator;
import org.joda.time.DateTimeFieldType;
public class TestDateTimeComparator {
public static void main(String[] args) {
//Two DateTime instances which have same month, date, and hour
//but different year, minutes and seconds
DateTime d1 = new DateTime(2001,05,12,7,0,0);
DateTime d2 = new DateTime(2014,05,12,7,30,45);
//Define the lower limit to be hour and upper limit to be month
DateTimeFieldType lowerLimit = DateTimeFieldType.hourOfDay();
DateTimeFieldType upperLimit = DateTimeFieldType.monthOfYear();
//Because of the upper and lower limits , the comparator shall only consider only those sub-elements
//within the lower and upper limits i.e.month, day and hour
//It shall ignore those sub-elements outside the lower and upper limits: i.e year, minute and second
DateTimeComparator dateTimeComparator = DateTimeComparator.getInstance(lowerLimit,upperLimit);
int result = dateTimeComparator.compare(d1, d2);
switch (result) {
case -1:
System.out.println("d1 is less than d2");
break;
case 0:
System.out.println("d1 is equal to d2");
break;
case 1:
System.out.println("d1 is greater than d2");
break;
default:
break;
}
}
}
我在这里找到了这个例子。
我想要采用与Java Time API相同的步骤,但不幸的是,我没有看到任何类似的比较器。
我如何才能比较特定的日期和时间字段,而不是使用Java Time API进行比较?
您可以使用Comparators
提供的通用帮助程序方法手动复制一些此类行为。
假设我们import static java.util.Comparators.comparing;
,我们可以在只比较月份的LocalDateTimes
上定义一个比较器:
Comparator<LocalDateTime> byMonth = comparing(LocalDateTime::getMonth);
或者只比较月份,日期和小时,如你的例子:
Comparator<LocalDateTime> byHourDayMonth = comparing(LocalDateTime::getMonth) //
.thenComparing(LocalDateTime::getDayOfMonth) //
.thenComparing(LocalDateTime::getHour);
这确实会让你处于手动决定订单的位置......不是很自动,而是采用更细致的控制。
链接地址: http://www.djcxy.com/p/90091.html上一篇: Joda time: DateTimeComparator. What is similar in Java 8 Time Api?