我在比较当前日期和从Database检索的日期时遇到了一些问题。我只是从DataBase中检索日期并存储在Date变量中,如下所示
String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));
SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = currentFormater.parse(due_date_task);
现在,我想要的是检查从DataBase检索的日期是否等同于CurrentDate。
Calendar currentDate = Calendar.getInstance();
Date date2 = currentDate.getTime();
if(date1.equals(date2))
System.out.println(“今日任务”);
我只想这样检查。谢谢提前
答案 0 :(得分: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);
答案 1 :(得分:1)
对于精确匹配(包括毫秒),请使用 getTime :
if(date.getTime() == date1.getTime()){
//do something
}
答案 2 :(得分: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
现在为数据库值创建Calendar对象,
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))