Search code examples
javadatetimecomparison

How to compare time string with current time in java?


I have a time string like "15:30" i want to compare that string with the current time. Please suggest something easy. And how to get the current time in hour minute format("HH:mm")


Solution

  • tl;dr

    LocalTime
        .now()
        .isAfter( 
            LocalTime.parse( "15:30" ) 
        )
    

    Details

    You should be thinking the other way around: How to get that string turned into a time value. You would not attempt math by turning your numbers into strings. So too with date-time values.

    Avoid the old bundled classes, java.util.Date and .Calendar as they are notoriously troublesome, flawed both in design and implementation. They are supplanted by the new java.time package in Java 8. And java.time was inspired by Joda-Time.

    Both java.time and Joda-Time offer a class to capture a time-of-day without any date to time zone: LocalTime.

    java.time

    Using the java.time classes built into Java, specifically LocalTime. Get the current time-of-day in your local time zone. Construct a time-of-day per your input string. Compare with the isBefore, isAfter, or isEqual methods.

    LocalTime now = LocalTime.now();
    LocalTime limit = LocalTime.parse( "15:30" );
    Boolean isLate = now.isAfter( limit );
    

    Better to specify your desired/expected time zone rather than rely implicitly on the JVM’s current default time zone.

    ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
    LocalTime now = LocalTime.now( z );  // Explicitly specify the desired/expected time zone.
    LocalTime limit = LocalTime.parse( "15:30" );
    Boolean isLate = now.isAfter( limit );
    

    Joda-Time

    The code in this case using the Joda-Time library happens to be nearly the same as the code seen above for java.time.

    Beware that the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.


    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.

    Where to obtain the java.time classes?

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.