androidandroid-timepickerdatetime-comparison

How to compare start time and end time in android?


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.


Solution

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