Check if a given time lies between two times regardless of date
You can use the Calendar
class in order to check.
For example:
try {
String string1 = "20:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
String string2 = "14:49:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
String someRandomTime = "01:00:00";
Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
}
} catch (ParseException e) {
e.printStackTrace();
}
tl;dr
20:11:13 < 01:00:00 < 14:49:00
LocalTime target = LocalTime.parse( "01:00:00" ) ;
Boolean targetInZone = (
target.isAfter( LocalTime.parse( "20:11:13" ) )
&&
target.isBefore( LocalTime.parse( "14:49:00" ) )
) ;
java.time.LocalTime
The java.time classes include LocalTime
to represent a time-of-day only without a date and without a time zone.
So what I want is, 20:11:13 < 01:00:00 < 14:49:00.
First we define the boundaries. Your input strings happen to comply with standard ISO 8601 formats. The java.time classes use ISO 8601 formats by default, so no need to specify a formatting pattern.
LocalTime start = LocalTime.parse( "20:11:13" );
LocalTime stop = LocalTime.parse( "14:49:00" );
And define our test case, the target 01:00:00
.
LocalTime target = LocalTime.parse( "01:00:00" );
Now we are set up to compare these LocalTime
objects. We want to see if the target is after the later time but before the earlier time. That means middle of the night in this case, between approximately 8 PM and 3 AM the next morning.
Boolean isTargetAfterStartAndBeforeStop = ( target.isAfter( start ) && target.isBefore( stop ) ) ;
That test can be more simply stated as “not between 3 AM and 8 PM”. We could then generalize to any pair of LocalTime
objects where we test for between if the start comes before the stop with a 24-hour clock, and not between if start comes after the stop (as in the case of this Question).
Further more, spans of time are usually handled with the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a "between" comparison, strictly speaking, would be “is the target equal to or later than start AND the target is before stop”, or more simply, “is target not before start AND before stop”.
Boolean isBetweenStartAndStopStrictlySpeaking =
( ( ! target.isBefore( start ) && target.isBefore( stop ) ) ;
If the start is after the stop, within a 24-hour clock, then assume we want the logic suggested in the Question (is after 8 PM but before 3 AM).
if( start.isAfter( stop ) ) {
return ! isBetweenStartAndStopStrictlySpeaking ;
} else {
return isBetweenStartAndStopStrictlySpeaking ;
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
-
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 brought some minor features and fixes.
-
Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
-
Android
- Later versions of Android (26+) bundle implementations of the java.time classes.
- For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
- If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
The answer given by @kocko works in only same day.
If start time "23:00:00" and end "02:00:00"[next day] and current time is "01:30:00" then result will false...
I modified the @kocko's answer to work perfectly
public static boolean isTimeBetweenTwoTime(String initialTime, String finalTime,
String currentTime) throws ParseException {
String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
if (initialTime.matches(reg) && finalTime.matches(reg) &&
currentTime.matches(reg))
{
boolean valid = false;
//Start Time
//all times are from java.util.Date
Date inTime = new SimpleDateFormat("HH:mm:ss").parse(initialTime);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(inTime);
//Current Time
Date checkTime = new SimpleDateFormat("HH:mm:ss").parse(currentTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(checkTime);
//End Time
Date finTime = new SimpleDateFormat("HH:mm:ss").parse(finalTime);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(finTime);
if (finalTime.compareTo(initialTime) < 0)
{
calendar2.add(Calendar.DATE, 1);
calendar3.add(Calendar.DATE, 1);
}
java.util.Date actualTime = calendar3.getTime();
if ((actualTime.after(calendar1.getTime()) ||
actualTime.compareTo(calendar1.getTime()) == 0) &&
actualTime.before(calendar2.getTime()))
{
valid = true;
return valid;
} else {
throw new IllegalArgumentException("Not a valid time, expecting
HH:MM:SS format");
}
}
}
Output
"07:00:00" - "17:30:00" - "15:30:00" [current] - true
"17:00:00" - "21:30:00" - "16:30:00" [current] - false
"23:00:00" - "04:00:00" - "02:00:00" [current] - true
"00:30:00" - "06:00:00" - "06:00:00" [current] - false
(I have included lower limit value to [upper limit value-1])
Modified @Surendra Jnawali' code. It fails
if current time is 23:40:00 i.e greater than start time and less than equals to 23:59:59.
All credit goes to the real owner
This is how it should be :This works perfect
public static boolean isTimeBetweenTwoTime(String argStartTime,
String argEndTime, String argCurrentTime) throws ParseException {
String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
//
if (argStartTime.matches(reg) && argEndTime.matches(reg)
&& argCurrentTime.matches(reg)) {
boolean valid = false;
// Start Time
java.util.Date startTime = new SimpleDateFormat("HH:mm:ss")
.parse(argStartTime);
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startTime);
// Current Time
java.util.Date currentTime = new SimpleDateFormat("HH:mm:ss")
.parse(argCurrentTime);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentTime);
// End Time
java.util.Date endTime = new SimpleDateFormat("HH:mm:ss")
.parse(argEndTime);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endTime);
//
if (currentTime.compareTo(endTime) < 0) {
currentCalendar.add(Calendar.DATE, 1);
currentTime = currentCalendar.getTime();
}
if (startTime.compareTo(endTime) < 0) {
startCalendar.add(Calendar.DATE, 1);
startTime = startCalendar.getTime();
}
//
if (currentTime.before(startTime)) {
System.out.println(" Time is Lesser ");
valid = false;
} else {
if (currentTime.after(endTime)) {
endCalendar.add(Calendar.DATE, 1);
endTime = endCalendar.getTime();
}
System.out.println("Comparing , Start Time /n " + startTime);
System.out.println("Comparing , End Time /n " + endTime);
System.out
.println("Comparing , Current Time /n " + currentTime);
if (currentTime.before(endTime)) {
System.out.println("RESULT, Time lies b/w");
valid = true;
} else {
valid = false;
System.out.println("RESULT, Time does not lies b/w");
}
}
return valid;
} else {
throw new IllegalArgumentException(
"Not a valid time, expecting HH:MM:SS format");
}
}
RESULT
Comparing , Start Time /n Thu Jan 01 23:00:00 IST 1970
Comparing , End Time /n Fri Jan 02 02:00:00 IST 1970
Comparing , Current Time /n Fri Jan 02 01:50:00 IST 1970
RESULT, Time lies b/w