Finava Vipul
Finava Vipul

Reputation: 998

How to compare current time with time stored in the database in Android

How to compare current date with value stored in the database? Currently my code looks as follows:

final String dDate = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
final String dTime = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(5)));
Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat formatter1 = new SimpleDateFormat("dd/M/yyyy");
String currentDate = formatter1.format(calendar1.getTime());

Calendar calendar2 = Calendar.getInstance();
SimpleDateFormat formatter2 = new SimpleDateFormat("h:mm");
String currentTime = formatter2.format(calendar2.getTime());
if(currentDate.compareTo(dDate)>=0) {
  if (currentDate.equals(currentDate)) {
    if (currentTime.compareTo(dTime) > 0) {
      myCheckBox.setChecked(true);
      myCheckBox.setEnabled(false);
    }
  }
}

Upvotes: 1

Views: 4407

Answers (2)

user4574256
user4574256

Reputation:

This code is working. Check out

Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat formatter1 = new SimpleDateFormat("dd/M/yyyy h:mm");
String currentDate = formatter1.format(calendar1.getTime());

final String dateString = cursor.getString(4);
final String timeString = cursor.getString(5);
String datadb =dateString+" "+timeString;

//  Toast.makeText(context,"databse date:-"+datadb+"Current Date :-"+currentDate,Toast.LENGTH_LONG).show();

if(currentDate.compareTo(datadb)>=0) {
    myCheckBox.setChecked(true);
    myCheckBox.setEnabled(false);
}

Upvotes: 4

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

You can't compare dates as strings reliably. You should first combine your date and time strings from the cursor into a single Date object and then compare it with the current timestamp.

Your code should look something like

final String dDate = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
final String dTime = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(5)));

SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy h:mm");
Date dbDateTime = formatter.parse(dDate + " " + dTime);

if(new Date().compareTo(dbDateTime) >= 0) {
    myCheckBox.setChecked(true);
    myCheckBox.setEnabled(false);
}

Here, SimpleDateFormat#parse() gives us a Date object containing both the date and time units initialized from the combined string. It can then simply be compared with a new Date() object which returns system's current date and time.

Upvotes: 3

Related Questions