Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")

like image 242
mayank sharma Avatar asked Jul 24 '14 07:07

mayank sharma


People also ask

Can you compare time in Java?

In order to compare time, we use the compareTo() method of the LocalTime class. The compareTo() method of the class compares two LocalTime objects.

How does HH MM compare to time in Java?

You can use compareTo . compareTo() method is defined in interface java.

How can I compare date and time in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How do you find the time in a string?

Here is our string. String strTime = "20:15:40"; Now, use the DateFormat to set the format for date.


4 Answers

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?

  • Java SE 8, Java SE 9, and later
  • Built-in.
  • 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
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
  • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
  • See How to use ThreeTenABP….

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.

like image 144
Basil Bourque Avatar answered Oct 20 '22 18:10

Basil Bourque


Just compare the strings as normal like so:

String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
String timeToCompare = "15:30";
boolean x = currentTime.equals(timeToCompare);

If the times are the same x will be true if they are not x will be false

like image 33
James Avatar answered Oct 20 '22 18:10

James


Following would get the time. You can than use it to compare

String currentTime=new SimpleDateFormat("HH:mm").format(new Date());
like image 25
Darshan Lila Avatar answered Oct 20 '22 18:10

Darshan Lila


I have a similar situation where I need to compare time string like "15:30" with the current time. I am using Java 7 so I can not use Basil Bourque's solution. So I have implemented one method which takes one string like "15:30" and check with current time and returns true if current time is after input time.

public static boolean checkSlaMissedOrNot(String sla) throws ParseException {
        boolean slaMissedOrnot = false;
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(sla.substring(0, 2)));
        cal.set(Calendar.MINUTE, Integer.parseInt(sla.substring(3)));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        if (Calendar.getInstance().after(cal)) {
            System.out.println("it's SLA missed");
            slaMissedOrnot = true;
        } else {
            System.out.println("it's fine & not SLA missed");
        }
        return slaMissedOrnot;
    }

Calendar has other use full methods like after(Object when)

Returns whether this Calendar represents a time after the time represented by the specified Object. You can use this method also to compare time string with the current time.

like image 39
Bacteria Avatar answered Oct 20 '22 17:10

Bacteria