我有日期数组。例如10个日期。我需要计算每个日期 - 这是本周或上周。怎么做到这个?
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;
}
我通过List<Receipt>
,如果收据上有本周的日期,我将其添加到新列表中。但它不起作用。
答案 0 :(得分:1)
使用类似的东西进行比较:
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。为了获得更正确的结果,您也可以检查年份(不仅仅是一年中的一周),您可以这样做:int year = c.get(Calendar.YEAR);
http://developer.android.com/reference/java/util/Calendar.html#WEEK_OF_YEAR
答案 1 :(得分:0)
创建方法比较日期
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
}}
在您的方法中调用此
if (isTheSameWeek(receiptList.get(i).getCreatedDate())){