I think this is more suitable solution for you.
/**
* @author Niravdas
*/
public class TimeDiff {
String[] titles = {"apple", "cherry", "coconut", "banana", "lemon"};
String[] times = {"04:21 AM", "12:01 PM", "03:32 PM", "06:30 PM", "08:04 PM"};
String findingAfter = "09:21 PM";
public TimeDiff() {
int time[] = nextTimeArrayIndex(findingAfter, times);
if (time[0] >= 0) {
System.out.println("NEXT TIME FOR (" + findingAfter + ") is: " + titles[time[0]] + "(" + times[time[0]] + ") after (" + time[1] + ") Hour And (" + time[2] + ") Minutes.");
}
}
public static void main(String argv[]) {
new TimeDiff();
}
int[] nextTimeArrayIndex(String Finding, String[] fromArray) {
int shortest = -1, shortestsec = -1;
long minsecdif = (24 * 60 * 60 + 1), minsec = (24 * 60 * 60 + 1);
int hr = Integer.parseInt(Finding.substring(0, 2));
int min = Integer.parseInt(Finding.substring(3, 5));
long seconds = convertToSec(hr, min, 0, Finding.substring(Finding.length() - 2));
for (int i = 0; i < fromArray.length; i++) {
int temphr = Integer.parseInt(fromArray[i].substring(0, 2));
int tempmin = Integer.parseInt(fromArray[i].substring(3, 5));
long tempsec = convertToSec(temphr, tempmin, 0, fromArray[i].substring(Finding.length() - 2));
if ((tempsec - seconds) > 0 && minsecdif > (tempsec - seconds)) {
minsecdif = (tempsec - seconds);
shortest = i;
}
if (minsec > tempsec) {
minsec = tempsec;
shortestsec = i;
}
}
int[] data = {0, 0, 0};
if (shortest != -1) {
data[0] = shortest;
data[1] = (int) (minsecdif / 60) / 60;
data[2] = (int) (minsecdif / 60) % 60;
} else {
data[0] = (int) shortestsec;
long tomorrowTimeDiff = (convertToSec(11, 59, 59, "PM") + 1 - seconds) + minsec;
data[1] = (int) (tomorrowTimeDiff / 60) / 60;
data[2] = (int) (tomorrowTimeDiff / 60) % 60;
}
return data;
}
long convertToSec(int hr, int min, int sec, String AMorPM) {
if (hr == 12) {
hr = 0;
}
long secs = (hr * 60 * 60) + (min * 60) + sec;
if (AMorPM.equalsIgnoreCase("PM")) {
secs += (12 * 60 * 60);
}
return secs;
}
}
here notice that tomorrowTimeDiff() mathod body has some change.
i think now it works proper for your program.
you also mentioned that you want to execute this function per second , This may help you.