乔达时间:日期时间比较器.Java 8 Time API 中有什么相似之处



有了Joda Time,你可以做一件非常酷的事情,例如:

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 时间 API 仅比较某些日期和时间字段而不比较其他日期和时间字段?

您可以使用 Comparator 上提供的通用帮助程序方法手动复制其中一些行为。

假设我们import static java.util.Comparator.comparing; ,我们可以在LocalDateTimes上定义一个仅比较月份的比较器:

Comparator<LocalDateTime> byMonth = comparing(LocalDateTime::getMonth);

或者仅比较月、日和小时,如您的示例所示:

Comparator<LocalDateTime> byHourDayMonth = comparing(LocalDateTime::getMonth) //
  .thenComparing(LocalDateTime::getDayOfMonth) //
  .thenComparing(LocalDateTime::getHour);

这确实使您处于手动决定顺序的位置...不完全是自动的,但有一些更细粒度的控制。

最新更新