I want to make a function to compare with the estimated time and actual time.
if estimated time = actual time + 15 minutes return delay
for example: estimated time = "09:00" actual time = "09:15" late
How can i do it in android java ?
I want to make a function to compare with the estimated time and actual time.
if estimated time = actual time + 15 minutes return delay
for example: estimated time = "09:00" actual time = "09:15" late
How can i do it in android java ?
Quick solution to be able to use parameters easily is to use Duration.
You can get the duration between to "time". From this, you can easily check of this is in a valid delay or not comparing two Duration.
Using Duration.between with two LocalTime, you will get the duration between the two. Then you just need to compare this with a specific duration of time, something like this :
//Our times for this test.
LocalTime lt1 = LocalTime.of(9, 0);
LocalTime lt2 = LocalTime.of(9, 10);
//A duration of 15minutes, used to validate the difference between the two times
Duration delay = Duration.ofMinutes(15);
//A duration between two times
Duration d = Duration.between(lt1, lt2);
//Is less than, or equal to the duration.
boolean isValid = d.compareTo(delay) <= 0;
Using :
import java.time.Duration;
import java.time.LocalTime;
A more complete test code
LocalTime lt1 = LocalTime.of(9, 0);
LocalTime lt2 = LocalTime.of(9, 10);
LocalTime lt3 = LocalTime.of(9, 15);
LocalTime lt4 = LocalTime.of(9, 20);
Duration delay = Duration.ofMinutes(15);
System.out.format("%s and %s as more than %s delay : %s%n", lt1, lt2, delay, Duration.between(lt1, lt2).compareTo(delay));
System.out.format("%s and %s as more than %s delay : %s%n", lt1, lt3, delay, Duration.between(lt1, lt3).compareTo(delay));
System.out.format("%s and %s as more than %s delay : %s%n", lt1, lt4, delay, Duration.between(lt1, lt4).compareTo(delay));
Output :
09:00 and 09:10 as more than PT15M delay : -1
09:00 and 09:15 as more than PT15M delay : 0
09:00 and 09:20 as more than PT15M delay : 1
You can easily use different Duration values and it is not complicated to get a LocalTime from a String, a LocalDateTime or even a Date.
private void compareTime(String lastTime) {
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa", Locale.US);
String currentTime = format.format(new Date(System.currentTimeMillis()));
Date date2 = null;
Date date1 = null;
try {
date1 = format.parse(lastTime);
date2 = format.parse(currentTime);
} catch (ParseException e) {
e.printStackTrace();
}
assert date2 != null;
long difference = (date2.getTime() - date1.getTime()) / 1000;
long hours = difference % (24 * 3600) / 3600; // Calculating Hours
long minute = difference % 3600 / 60; // Calculating minutes if there is any minutes difference
long min = minute + (hours * 60);
if (min > 24 || min < -24) {
}
}
Your lastTime should be in "hh:mm:ss aa" this format as same to currentTime.