Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 698
Reena Avatar asked Nov 18 '14 05:11

Reena


1 Answers

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;
}
like image 124
Pratik Dasa Avatar answered Oct 28 '22 01:10

Pratik Dasa