1

I am allowing user to select a time for that i am using TimePicker in my Activity, and getting result in this format: 03:51 PM

Now i have a time range like - 07:00 PM to 10:00 PM

If selected time by user matches to time defined in time range, then need to show message "Could be Dangerous"

So finally i would like to know that How can i check that selected time within time range or not ?

I have already gone through to this Link

Community
  • 1
  • 1
Oreo
  • 2,586
  • 8
  • 38
  • 63

3 Answers3

1

I suggest you use jodatime for this. It's a very powerful lib.
joda
Then you can implement like below

LocalTime startTime = LocalTime.parse("07:00 PM", DateTimeFormat.forPattern("KK:mm a"));
    LocalTime endTime = LocalTime.parse("10:00 PM", DateTimeFormat.forPattern("KK:mm a"));

    LocalTime selected = new LocalTime(hourOfDay, minute);
    if (selected.isAfter(startTime) && selected.isBefore(endTime)) {
      // do your work
    }
justHooman
  • 3,044
  • 2
  • 17
  • 15
  • please have a look at this issue: http://stackoverflow.com/questions/31429438/joda-localtime-meridiem-parse – Oreo Jul 15 '15 at 12:55
1

you achieve it using following code...

TimePickerDialog.OnTimeSetListener lisTime = new TimePickerDialog.OnTimeSetListener() {

            @Override 
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
                // TODO Auto-generated method stub 
               if((hourOfDay >= 19 && hourOfDay < 22)  || (hourOfDay == 22 && minute == 0))
               {

                    // you can code here time is between 7PM to 10PM
               }
               else
               {
                    // continition not satiesfied
               }


            } 
        }; 
DjP
  • 4,537
  • 2
  • 25
  • 34
0

Convert the two strings to Date objects (which are also time objects) then Create a new Date object.

This will contain the current time. Use the Date.before() and Date.after() methods to determine if you are in the time interval.

public static final String inputFormat = "HH:mm";

private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;

private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";

SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);

private void compareDates(){
    Calendar now = Calendar.getInstance();

    int hour = now.get(Calendar.HOUR);
    int minute = now.get(Calendar.MINUTE);

    date = parseDate(hour + ":" + minute);
    dateCompareOne = parseDate(compareStringOne);
    dateCompareTwo = parseDate(compareStringTwo);

    if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
        //yada yada
    }
}

private Date parseDate(String date) {

    try {
        return inputParser.parse(date);
    } catch (java.text.ParseException e) {
        return new Date(0);
    }
}
Gopal Singh Sirvi
  • 4,539
  • 5
  • 33
  • 55