Krish
Krish

Reputation: 4232

How to compare time ranges?

Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog

start time:06:00 end time:23:00 selected time from time picker dialog:12:23

above timing not suitable for below code can some one help me please

     String pattern = "hh:mm";                                            
     SimpleDateFormat sdf = new SimpleDateFormat(pattern);
     Date date1 = sdf.parse(startTime);
     Date date2 = sdf.parse(endTime);
     Date date3 = sdf.parse(selectedTime);
     if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {         


     }
     else {
           Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();                                         
      }

Upvotes: 0

Views: 546

Answers (2)

SpiritCrusher
SpiritCrusher

Reputation: 21043

You can use code below .

 String pattern = "HH:mm";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    try {
        Date date1 = sdf.parse(startTime);
        Date date2 = sdf.parse(endTime);
        Date date3 = sdf.parse(selectedTime);
        if (date3.compareTo(date1) >= 0 && date3.compareTo(date2) <= 0) {
            // Do your stuff
        } else {
            // Wrong time
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

h represents Hour in am/pm (1-12)

H represents Hour in day (0-23)

Your date is in 24 hour formate so you should use H instead of h.

Upvotes: 1

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

You should use compareTo().

CompareTo method must return negative number if current object is less than other object, positive number if current object is greater than other object and zero if both objects are equal to each other.

Code Reference

if (date1.compareTo(date2) < 0)
{
Log.d("RESULT","date1 older than date2"); 
}
else
{
 Log.d("RESULT","date2 older than date1"); 
}

NOTE

Make sure your TIME format is perfect.

Upvotes: 1

Related Questions