1

我在比较当前日期和从数据库中检索的日期时遇到了一些问题。我只是从数据库中检索日期并存储在这样的日期变量中

String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));

SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = currentFormater.parse(due_date_task);

现在,我想要的是检查从数据库中检索到的日期是否等同于 CurrentDate。

Calendar currentDate = Calendar.getInstance();
Date date2 = currentDate.getTime();

if(date1.equals(date2)) 

System.out.println("今天的任务");

我只是想这样检查。提前谢谢

4

3 回答 3

1

您可以使用此功能:

private boolean compareDates(Calendar objCal1, Calendar objCal2) {

  return ((objCal1.get(Calendar.YEAR) == objCal2.get(Calendar.YEAR))
    && (objCal1.get(Calendar.DAY_OF_YEAR) == objCal2.get(Calendar.DAY_OF_YEAR)));
}

创建日历对象:

Calendar objCal1 = new GregorianCalendar().setTime(date);
Calendar objCal2 = new GregorianCalendar().setTime(date1);
于 2012-04-04T10:04:15.047 回答
1

对于包括毫秒在内的精确匹配,请使用getTime

if(date.getTime() == date1.getTime()){
   //do something
} 
于 2012-04-04T10:04:50.707 回答
0

试试这种方式来获取当前日期,

Calendar calCurr = Calendar.getInstance();
Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis()); // see what it gives? dont know why?
Date date = new Date();
calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());// so added one month to it
Log.i("Time in mili of Current - after update", ""+calCurr.getTimeInMillis()); // now get correct

现在为数据库值创建日历对象,

String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));      

SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");      
Date date = currentFormater.parse(due_date_task);     
Calendar start = Calendar.getInstance();
start.set(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());

现在比较两个日历对象

if(calCurr.equals(start))
于 2012-04-04T10:12:37.303 回答