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

耗尽温柔 提交于 2019-12-12 01:22:40

问题


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.


回答1:


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




回答2:


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())){


来源:https://stackoverflow.com/questions/30862932/how-to-determine-whether-the-date-of-this-week-or-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!