I have tried with the below code to compare two times:
SimpleDateFormat sdf = new SimpleDateFormat(\"hh:mm\");
Date inTime = sdf.parse(\"11:00\");
Use java.time.
LocalTime
.parse( "12:00" )
.isAfter(
LocalTime.parse( "11:00" )
)
You have three problems:
Date
& SimpleDateFormat
) that were supplanted years ago by the modern java.time classes.hh:mm
should have been uppercase for 24-hour clock rather than 12-hour clock: HH:mm
. 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.
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?