假设我有一个Collection
,DateTimes
我如何过滤所有DateTime
时间在 10h00m 和 12h30m 之间的对象?
例如:
new DateTime(2013,1,1,10,0)
- 是正确的,
new DateTime(2013,1,1,16,0)
- 不是。
月、年、日等参数并不重要。有任何想法吗?
您可以在这里真正利用 joda 的LocalTime
课程:
LocalTime lowerBound = new LocalTime(10, 0);
LocalTime upperBound = new LocalTime(12, 30);
List<DateTime> filtered = new ArrayList<>();
for (DateTime dateTime : originals) {
LocalTime localTime = new LocalTime(dateTime);
if (lowerBound.isBefore(localTime) && upperBound.isAfter(localTime)) {
filtered.add(dateTime);
}
}
您可能需要调整包容性或排斥性,但LocalTime
is Comparable
,最重要的是,它具有有助于提高可读性的友好比较方法。
List<DateTime> filtered = new ArrayList<>();
for (DateTime dt : mycollection){
if (dt.getHourOfDay >= 10 && dt.getHourOfDay <= 12){
if (dt.getHourOfDay != 12 ||
(dt.getHourOfDay == 12 && dt.getMinuteOfHour <= 30)){
filtered.add(dt);
}
}
}
为简单起见,我使用了Calendar
类型类。
这应该可以解决您的请求:
public List<Calendar> filterDateTime(ArrayList<Calendar> dateTimeList) {
List<Calendar> dateTimeFilteredList = new ArrayList<Calendar>();
for (int i=0;i < dateTimeList.size(); i++) {
Calendar currentDateTime = Calendar.getInstance();
currentDateTime.setTime(dateTimeList.get(i).getTime());
// Setting the bottom dateTime value
Calendar filterFrom = Calendar.getInstance();
filterFrom.setTime(currentDateTime.getTime());
filterFrom.set(Calendar.HOUR_OF_DAY, 10);
filterFrom.set(Calendar.MINUTE, 00);
// Setting the upper dateTime value
Calendar filterTo = Calendar.getInstance();
filterTo.setTime(currentDateTime.getTime());
filterTo.set(Calendar.HOUR_OF_DAY, 12);
filterTo.set(Calendar.MINUTE, 30);
if(currentDateTime.after(filterFrom) && currentDateTime.before(filterTo)) {
dateTimeList.add(currentDateTime);
}
}
return dateTimeFilteredList;
}