use*_*011 8 java jodatime java-8 java-time
使用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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里找到了这个例子.
我想使用Java Time API执行相同的步骤,但不幸的是,我没有看到任何类似的Comparators.
如何仅使用Java Time API比较某些日期和时间字段而不与其他字段进行比较?
您可以使用提供的通用帮助程序方法复制一些此类行为,更多手动Comparator.
假设我们import static java.util.Comparator.comparing;,我们可以定义比较器LocalDateTimes,只比较月份:
Comparator<LocalDateTime> byMonth = comparing(LocalDateTime::getMonth);
Run Code Online (Sandbox Code Playgroud)
或者只比较月,日和小时的那个,如你的例子中所示:
Comparator<LocalDateTime> byHourDayMonth = comparing(LocalDateTime::getMonth) //
.thenComparing(LocalDateTime::getDayOfMonth) //
.thenComparing(LocalDateTime::getHour);
Run Code Online (Sandbox Code Playgroud)
这确实让你处于手动决定顺序的位置......不是那么自动但是有一些更精细的控制.