2

I have a java Multimap that contains an identifier mapped to a start date and an end date.

SetMultiMap<String,List<Date>> mymap = LinkedHashMultimap.create();

I am using this map in another method, where I want to retrieve all the keys whose end date is less than 1 week ago.

I tried this:

DateTime lastWeek_joda = new DateTime().minusDays(7);
Date end_date = lastWeek_joda.toDate();

now i iterate as follows:

for (Map.Entry<String,List<date>> entry : mymap.entries()) 
    String key = entry.getKey();
    List<Date> value = entry.getValue();
    if (end_date.equals(value.get(1))) {
        key_set.add(key);
    }
}

This doesnt return me the expected result? Can this be done any easier/different? Thanks in advance.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
Tania
  • 1,855
  • 1
  • 15
  • 38
  • you should use `compareTo()`. By using `equals()` you'll get only datetimes precisely the same as datetime 1 week ago. – Alex Salauyou Feb 25 '16 at 15:50
  • 1
    Try see [how Dates can be compared](http://stackoverflow.com/a/2592513/1346996). – António Ribeiro Feb 25 '16 at 15:59
  • use calendar class in Java to check date range.it provides lot of functionality to filter date.http://stackoverflow.com/questions/17210839/get-last-week-date-range-for-a-date-in-java – gihan-maduranga Feb 25 '16 at 16:16

2 Answers2

2

You are checking for dates that exactly equal the week-prior-date. Instead, use compareTo and check if the week-prior-date is greater than (later than) the current value.

for (Map.Entry<String,List<date>> entry : mymap.entries()) 
    String key = entry.getKey();
    List<Date> value = entry.getValue();
    if (end_date.compareTo(value.get(1)) > 0) {
        key_set.add(key);
    }
}
James Wierzba
  • 16,176
  • 14
  • 79
  • 120
1
 for (Map.Entry<String,List<date>> entry : mymap.entries()) 
    String key = entry.getKey();
    List<Date> value = entry.getValue();
    if (checkDateRange(value.get(1))) {
        key_set.add(key);
    }
}

public boolean checkDateRange(Date tDate)  {
    Date date = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int i = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
    c.add(Calendar.DATE, -i - 7);
    Date start = c.getTime();
    c.add(Calendar.DATE, 6);
    Date end = c.getTime();

    //your logic goes here
     if(start<=tDate<=end){
        return true;
     }
    return false;
   }
gihan-maduranga
  • 4,381
  • 5
  • 41
  • 74