How to compare start time and end time in android?

7.8k views Asked by At

My Question is How to compare two time between startTime and endTime,

Comparison two time.

  1. Start time
  2. End time.

I am using the TimePickerDialog for fetching time and I am using one method Which pass the parameter like long for startTime and endTime, I am using like this,

//Method:
boolean isTimeAfter(long startTime, long endTime) {
    if (endTime < startTime) {
        return false;
    } else {
        return true;
    }
}

String strStartTime = edtStartTime.getText().toString();
String strEndTime = edtEndTime.getText().toString();

long lStartTime = Long.valueOf(strStartTime);
long lEndTime = Long.valueOf(strEndTime);

if (isTimeAfter(lStartTime, lEndTime)) {

} else {

}

Get The Error:

java.lang.NumberFormatException: Invalid long: "10:52"

How to compare two time. Please suggest me.

2

There are 2 answers

2
Pratik Dasa On BEST ANSWER

First of all you have to convert your time string in to SimpleDateFormat like below:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
Date inTime = sdf.parse(strStartTime);
Date outTime = sdf.parse(strEndTime);

Then call your method like below:

if (isTimeAfter(inTime, outTime)) {

} else {

}

boolean isTimeAfter(Date startTime, Date endTime) {
    if (endTime.before(startTime)) { //Same way you can check with after() method also.
        return false;
    } else {
        return true;
    }
}

Also you can compare, greater & less startTime & endTime.

int dateDelta = inTime.compareTo(outTime);
 switch (dateDelta) {
    case 0:
          //startTime and endTime not **Equal**
    break;
    case 1:
          //endTime is **Greater** then startTime 
    break;
    case -1:
          //startTime is **Greater** then endTime
    break;
}
1
Ashwin H On

What about this :

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");

 public static boolean isTimeAfter(Date startTime, Date endTime) {
            return !endTime.before(startTime);
        }
    }

try {
        Date inTime = sdf.parse(mEntryTime);
        Date outTime = sdf.parse(mExitTime);
        if (Config.isTimeAfter(inTime, outTime)) {
            //Toast.makeText(AddActivity.this, "Time validation success", Toast.LENGTH_LONG).show();
        } 
        else {
            Toast.makeText(AddActivity.this, "Exit time must be greater then entry time", Toast.LENGTH_LONG).show();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        //Toast.makeText(AddActivity.this, "Parse error", Toast.LENGTH_LONG).show();
    }