Comparing two times in android

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....


tl;dr

Use java.time.

LocalTime
.parse( "12:00" )
.isAfter(
    LocalTime.parse( "11:00" ) 
)

java.time

You have three problems:

  • You are using terrible old date-time classes (Date & SimpleDateFormat) that were supplanted years ago by the modern java.time classes.
  • Your format of hh:mm should have been uppercase for 24-hour clock rather than 12-hour clock: HH:mm.
  • You are inappropriately trying to represent a time-of-day with a class meant for date-with-time-of-day values.

Use LocalTime. This class represents a time-of-day without a date and without a time zone.

LocalTime start = LocalTime.parse( "11:00" ) ;
LocalTime stop = LocalTime.parse( "12:00" ) ;

You can compare.

boolean isStopAfterStart = stop.isAfter( start ) ;

Calculate the elapsed time as a Duration.

Duration d = Duration.between( start , stop ) ;

d.toString(): PT1H

You can also ask the Duration if it is negative, as another way to detect the stop time being before the start.

boolean isStopBeforeStart = d.isNegative() ;

Caveat: Working on time-of-day without the context of a date and a time zone can produce unrealistic results. That approach ignores the anomalies that occur in time zones such as Daylight Saving Time (DST) and other shifts to the wall-clock time used by the people of a particular region. An hour can repeat, or be skipped. A day can be 23, 23.5, 23.75, 25, or other number of hours long.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….