5

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.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
Reena
  • 563
  • 4
  • 11
  • 22

2 Answers2

8

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;
}
Nigam Patro
  • 2,760
  • 1
  • 18
  • 33
Pratik Dasa
  • 7,439
  • 4
  • 30
  • 44
0

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();
    }
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
Ashwin H
  • 695
  • 7
  • 24
  • what could be this " }" after the function "isTimeAfter" and before try present. You should revue your code :). – DINA TAKLIT May 10 '19 at 05:44