Search code examples
androidtimetoast

Comparing two times in android


I have tried with the below code to compare two times:

   SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
    Date inTime = sdf.parse("11:00");
    Date outTime = sdf.parse("10:00");

    if(inTime.compareTo(outTime) > 0){
    Toast.makeText(this, "Out time should be greater than In time", Toast.LENGTH_SHORT).show();
    }

Above code is working fine.

But if I give in time as 11:00 and out time as 12:00, I am getting above toast message.

I am getting above toast message if I give out time from 12:00 to 12:59. In other cases above code is working fine.

Where I am doing wrong. Please help me.


Solution

  • Change SimpleDateFormat like below...

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    

    Below are the patterns:

    H   Hour in day (0-23)  Number  0
    k   Hour in day (1-24)  Number  24
    K   Hour in am/pm (0-11)    Number  0
    h   Hour in am/pm (1-12)    Number  12
    

    This will work....