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

With Joda Time, you can do 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 iemonth, day and hour //It shall ignore those sub-elements outside the lower and upper limits: ie 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 the Java Time API, but unfortunately I do not see such comparators.

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

+7
java java-8 jodatime java-time
source share
1 answer

You can repeat some of these steps, a little more manually, using the general-purpose helper methods provided by Comparators .

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

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

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

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

This leaves you in a position where you manually determine the order ... not entirely automatic, but with finer control.

+4
source share

All Articles