Skip to content Skip to sidebar Skip to footer

Date Comparison In Android

I'm facing some problems in comparing the current date and the date which is retrieved from Database.I just retrieved date from DataBase and Stored in a Date variable like this Str

Solution 1:

For exact match including milliseconds, use getTime:

if(date.getTime() == date1.getTime()){
   //do something
} 

Solution 2:

You can use this function:

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)));
}

creating the calendar objects:

CalendarobjCal1=newGregorianCalendar().setTime(date);
CalendarobjCal2=newGregorianCalendar().setTime(date1);

Solution 3:

Try this way to get the current date,

CalendarcalCurr= Calendar.getInstance();
Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis()); // see what it gives? dont know why?Datedate=newDate();
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

now create Calendar object for database value,

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

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

and now Compare both the Calendar objects

if(calCurr.equals(start))

Post a Comment for "Date Comparison In Android"