Reputation: 67
I am trying to calculate remaining time for bus timetable. So I stored all list of tables in ArrayList, and I want to calculate the remaining time only just for one timetable at a time. For example, assume the list has 8:00 and 8:15, and the current time is 7:55. What I want is that calculate the remaining time with 8:00 not 8:15, and also if the current time is 8:01, the calculation should be happening with 8:15 not 8:00. If you guys help me with that (any links or sample methods), that would be fantastic.
Upvotes: 0
Views: 513
Reputation: 347244
A lot comes down to how you are storing your time information, for example, if you are using something like Date
or LocalTime
, you can simply sort the List
of times and use Collections.binarySearch
to find a suitable time...
List<LocalTime> times = new ArrayList<>(25);
times.add(LocalTime.of(9, 0));
times.add(LocalTime.of(8, 45));
times.add(LocalTime.of(8, 30));
times.add(LocalTime.of(8, 15));
times.add(LocalTime.of(8, 0));
times.add(LocalTime.of(7, 45));
times.add(LocalTime.of(7, 30));
times.add(LocalTime.of(7, 15));
times.add(LocalTime.of(7, 0));
int result = Collections.binarySearch(times, LocalTime.of(7, 55), new Comparator<LocalTime>() {
@Override
public int compare(LocalTime o1, LocalTime o2) {
LocalTime startRange = o1.minusMinutes(15);
LocalTime endRange = o1;
if ((o2.equals(o1) || startRange.isBefore(o2)) && (o2.equals(o1) || o2.isBefore(o1))) {
return 0;
}
return o1.compareTo(o2);
}
});
if (result >= 0) {
System.out.println(times.get(result));
}
Which outputs 08:00
Now,
if ((o2.equals(o1) || startRange.isBefore(o2)) && (o2.equals(o1) || o2.isBefore(o1))) {
Is matching an exact period (7:45-8:00 inclusive, for example), this might not be what you want (so it's 8:00, you've probably missed the bus ;)) so you might be able to use something like
if (startRange.isBefore(o2) && o2.isBefore(o1)) {
which will match 7:46-7:59 inclusive, for example or combinations based on your needs...
Upvotes: 1
Reputation: 11180
Assuming the list is sorted, you can loop through the list and return the first element which the difference is positive.
Pseudocode:
for each time in timetable:
difference = time - current_time
if difference > 0: return difference
Upvotes: 0