1

假设我有一个CollectionDateTimes我如何过滤所有DateTime时间在 10h00m 和 12h30m 之间的对象?

例如:

new DateTime(2013,1,1,10,0)- 是正确的,

new DateTime(2013,1,1,16,0)- 不是。

月、年、日等参数并不重要。有任何想法吗?

4

3 回答 3

3

您可以在这里真正利用 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);
    }
}

您可能需要调整包容性或排斥性,但LocalTimeis Comparable,最重要的是,它具有有助于提高可读性的友好比较方法。

于 2013-07-25T14:59:10.090 回答
1
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);
        }
    }
}
于 2013-07-25T12:45:33.060 回答
0

为简单起见,我使用了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;
  }
于 2013-07-25T12:50:12.677 回答