how to determine whether the date of this week or

2019-09-07 08:58发布

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.

2条回答
贼婆χ
2楼-- · 2019-09-07 09:45

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

查看更多
Melony?
3楼-- · 2019-09-07 09:46

Create a method compare dates

public boolean isTheSameWeek (Date date ){

Calendar c=Calendar.getInstance();
year1=c.get(c.YEAR);
week1=c.get(c.WEEK_OF_YEAR);

Calendar c1=Calendar.getInstance();
c.setTimeInMillis(date.getTime())
year2=c.get(c.YEAR);
week2=c.get(c.WEEK_OF_YEAR);

if(year1 == year2){
       if(week1 == week2}{
       return true;

       }
    }
return false
}}

In your method call this

     if (isTheSameWeek(receiptList.get(i).getCreatedDate())){
查看更多
登录 后发表回答