Cherry
Cherry

Reputation: 33598

How to extract joda DateTime belonging to specific time range?

Suppose I have a Collection of DateTimes, how I can filter all DateTime objects that have a time between 10h00m and 12h30m?

For example:

new DateTime(2013,1,1,10,0) - is right,

new DateTime(2013,1,1,16,0) - is not.

Parameters like month, year, day are not significant. Any ideas?

Upvotes: 1

Views: 161

Answers (3)

bowmore
bowmore

Reputation: 11310

You can really take advantage of joda's LocalTime class here :

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

You may need to tweak for inclusive or exclusive, but LocalTime is Comparable, and on top of that, has friendly compare methods that help readability.

Upvotes: 3

Jannis Alexakis
Jannis Alexakis

Reputation: 1319

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

Upvotes: 1

araknoid
araknoid

Reputation: 3125

For simplicity i used Calendar type class.

This should solve your request:

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

Upvotes: 0

Related Questions