Search code examples
androidandroid-date

how to determine whether the date of this week or last?


I have date array. For example 10 dates. I need calculate each date - it is this week or last week. How do make this?

private List<Receipt> getSectionPosition(List<Receipt> receiptList){
       List<Receipt> list = new ArrayList<>();
       Date now = new Date();
        for (int i = 0; i<receiptList.size(); i++){
            if (receiptList.get(i).getCreatedDate().compareTo(now)==0){
                list.add(receiptList.get(i));
            }
        }
       return list;
    }

i pass List<Receipt> and if receipt has date on this week i add it in new list. but it is not work.


Solution

  • Use something like this for comparing:

    private List<Receipt> getSectionPosition(List<Receipt> receiptList){
       List<Receipt> list = new ArrayList<>();
       Date now = new Date();
       Calendar c = Calendar.getInstance();
       c.setTime(now);
       int currentWeek = c.get(Calendar.WEEK_OF_YEAR);
       for (int i = 0; i<receiptList.size(); i++){
           c.setTime(receiptList.get(i).getCreatedDate());
           int createdDateWeek = c.get(Calendar.WEEK_OF_YEAR);
    
           if (currentWeek == createdDateWeek){
               list.add(receiptList.get(i));
           }
       }
       return list;
    }
    

    P.S. for more correct results, you could check the year, too (not just the week of the year), which you could do like this: int year = c.get(Calendar.YEAR); http://developer.android.com/reference/java/util/Calendar.html#WEEK_OF_YEAR