How to compare start time and end time in android?
Asked Answered
P

2

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.

Percussion answered 18/11, 2014 at 5:38 Comment(0)
E
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;
}
Enroot answered 18/11, 2014 at 5:47 Comment(2)
there is issue in case of 12AM and 12 PMPalatine
Have you tried it? May be you have to convert time in 24 hours format so will not create problem. @HeenaAroraEnroot
E
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();
    }
Earnestineearnings answered 10/5, 2019 at 5:19 Comment(1)
what could be this " }" after the function "isTimeAfter" and before try present. You should revue your code :).Ruberta

© 2022 - 2024 — McMap. All rights reserved.