java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
String strStartTime = "22:30:00", strStopTime = "03:30:00", strTestTime = "01:14:23";
LocalDate today = LocalDate.now();
LocalDateTime startTime = today.atTime(LocalTime.parse(strStartTime));
LocalDateTime stopTime = today.atTime(LocalTime.parse(strStopTime));
if (stopTime.isBefore(startTime))
stopTime = stopTime.plusDays(1);
LocalDateTime testTime = today.atTime(LocalTime.parse(strTestTime));
if (testTime.isBefore(startTime))
testTime = testTime.plusDays(1);
if (!testTime.isBefore(startTime) && !testTime.isAfter(stopTime))
System.out.println(strTestTime + " is at or after " + strStartTime + " and is before or at " + strStopTime);
}
}
Output:
01:14:23 is at or after 22:30:00 and is before or at 03:30:00
ONLINE DEMO
Note: If the start time and stop time are not inclusive, change the condition as follows:
if (testTime.isAfter(startTime) && testTime.isBefore(stopTime))
System.out.println(strTestTime + " is after " + strStartTime + " and is before " + strStopTime);
Learn more about the modern Date-Time API from Trail: Date Time.
* 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.