我对这个问题感到难过。是否可以在指定日期之前将日期添加到arraylist中?没有运气试图找到答案。
这就是我打算这样做的方式。
try {
String format = min;
String format2 = format.substring(0,7);
String format3 = format.substring(7,format.length());
String finalFormat =format2+"20"+format3;
String finalFormatPart1 = finalFormat.substring(0, 2);
String finalFormatPart2 = finalFormat.substring(3, 6);
String finalFormatPart3 = finalFormat.substring(7, finalFormat.length());
String finalFormatcomplete =finalFormatPart1+" "+finalFormatPart2+" "+finalFormatPart3;
minDate = new SimpleDateFormat("dd MMM yyyy").parse(finalFormatcomplete);
Log.i("minDateTime", minDate.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date rightNow = Calendar.getInstance().getTime();
for(int i=1; i != 31; i++) {
Calendar calendar = Calendar.getInstance();
calendar.add(rightNow, -i);
beforeMin.add(dateToAdd);
}
但是,calendar.add()只接受int,int。有没有办法在指定日期之前将日期添加到arraylist中?
答案 0 :(得分:1)
您可以将上一个日期视为:
calender.add(Calendar.DATE, -1);
所以将代码更改为:
Calendar rightNow = Calendar.getInstance();
for (int i = 1; i <= 31; i++) {
rightNow.add(Calendar.DATE, -i);
Date dateToAdd = rightNow.getTime();
beforeMin.add(dateToAdd);
}
答案 1 :(得分:0)
添加元素并对其进行排序
添加比较器:
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject obj1, MyObject obj2) {
return obj1.getDateTime().compareTo(obj2.getDateTime());
}
});
下面是compareTo函数:
public int compareTo(MyObject obj) {
if (getDateTime() == null || obj.getDateTime() == null)
return 0;
return getDateTime().compareTo(obj.getDateTime());
}
答案 2 :(得分:0)
更改您的代码如下:
Calendar calendar = Calendar.getInstance();
for(int i=1; i < 31; i++)
{
calendar.add(Calendar.DATE, -1);
beforeMin.add(calendar.getTime());
}
答案 3 :(得分:0)
只需使用日期比较,如下所示
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2009-12-31");
Date date2 = sdf.parse("2010-01-31");
System.out.println(sdf.format(date1));
System.out.println(sdf.format(date2));
if(date1.after(date2)){
System.out.println("Date1 is after Date2");
}
if(date1.before(date2)){
System.out.println("Date1 is before Date2");
}
if(date1.equals(date2)){
System.out.println("Date1 is equal Date2");
}
希望这个答案对你朋友有帮助:))