Joda time: DateTimeComparator. What is similar in Java 8 Time Api?

With Joda Time, you are able to do a really cool things, for example:

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;
        }
    }
}

I found this example here.

I want to have the same steps but with Java Time API, but unfortunately, I do not see any similar Comparators.

How can I compare only certain date and time fields but not others with Java Time API?


You can replicate some of this behavior, a bit more manually, with the general-purpose helper methods provided on Comparators .

Assuming that we import static java.util.Comparators.comparing; , we can define a comparator on LocalDateTimes that compares only the month:

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

or one that compares only the month, day, and hour, as in your example:

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

This does leave you in the position of manually deciding the order... not quite as automatic but with some more fine-grained control.

链接地址: http://www.djcxy.com/p/90092.html

上一篇: Docker:重新连接到`docker exec`进程

下一篇: 乔达时间:DateTimeComparator。 Java 8 Time Api有什么相似之处?