You can parse the times into LocalTime
and then find the difference in terms of the desired unit (e.g. ChronoUnit.MINUTES
) using LocalTime#until
. Based on the value of the difference, you can make a decision.
Demo:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm a", Locale.US);
LocalTime time1 = LocalTime.parse("11:18 AM", dtf);
LocalTime time2 = LocalTime.parse("11:45 AM", dtf);
long minutes = Math.abs(time1.until(time2, ChronoUnit.MINUTES));
if (minutes > 15) {
System.out.println("Do this");
// ...
} else {
System.out.println("Do that");
// ...
}
}
}
Output:
Do this
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.