views:

263

answers:

3

I have first time as string '12:00:00' and another '19:00:00'

next how to check time portion of the day is within these time values?

A: 

Create calendar instances of the start and end times for the same day as your 'test' date. Then you can easily compare the calendar objects to determine if the current date is inside or outside the range.

Andreas_D
A: 

Instead of using the heavy weight classes, in your case you could do a simple string comparision to achieve the same:

  String from="12:00:00";
 String to ="19:00:00";
 String toCheck = "16:00:00";
 if ( toCheck.compareTo(from) >= 0 && toCheck.compareTo( to ) <= 0) {
     System.out.println("in range");
 }
 else {
     System.out.println("out of range");
 }

EDIT: Nice code

public class DateFilter {

    public static void main(String[] args) {

      String from="12:00:00";
      String to ="19:00:00";
      String toCheck = "16:00:00";
      System.out.println("inRange=" + isInRange( from, to, toCheck ));
    }

    public static boolean isInRange( String from, String to, String toCheck ) {
          return toCheck.compareTo(from) >= 0 && toCheck.compareTo( to ) <= 0;
      }
}
stacker
@Downvoter I use this in production for filtering ranges it's the fastest way, since it doesn't create useless objects. Drawback need 24h representation.
stacker
+2  A: 

Using Joda Time you could do something like this:

DateTime start = new DateTime(2010, 5, 25, 12, 0, 0, 0);
DateTime end = new DateTime(2010, 5, 25, 21, 0, 0, 0);
Interval interval = new Interval(start, end);
DateTime test = new DateTime(2010, 5, 25, 16, 0, 0, 0);
System.out.println(interval.contains(test));
Mark McLaren