Check Time lies in between 2 Time regardless of date – Android

If start time “23:00:00” and end “02:00:00″[next day] and current time is “01:30:00” then result will false…
Answer given below works perfect, just call isTimeBetweenTwoTime() function at your end and pass start time, end time and current time.

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  
       java.util.Date inTime = new SimpleDateFormat("HH:mm:ss").parse(initialTime);  
       Calendar calendar1 = Calendar.getInstance();  
       calendar1.setTime(inTime);  
       //Current Time  
       java.util.Date checkTime = new SimpleDateFormat("HH:mm:ss").parse(currentTime);  
       Calendar calendar3 = Calendar.getInstance();  
       calendar3.setTime(checkTime);  
       //End Time  
       java.util.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

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of