This example shows how to compare time in Java using LocalTime class isBefore() and isAfter() Methods.
The java.time.LocalTime class is an immutable class which represents a time without time-zone information.
Read more about LocalTime class with an example at https://www.javaguides.net/2018/08/java-8-localtime-class-api-guide.html.
The java.time.LocalTime class is an immutable class which represents a time without time-zone information.
Read more about LocalTime class with an example at https://www.javaguides.net/2018/08/java-8-localtime-class-api-guide.html.
Java LocalTime isBefore() and isAfter() Method Example
LocalTime class provides below APIs to compare LocalTime objects in Java.
- int compareTo(LocalTime other) - Compares this time to another time.
- boolean isAfter(LocalTime other) - Checks if this time is after the specified time.
- boolean isBefore(LocalTime other) - Checks if this time is before the specified time.
import java.time.LocalTime; /** * Program to demonstrate LocalTime Class APIs. * @author javaguides.net * */ public class LocalTimeExample { public static void main(String[] args) { compareLocalTimeObjects(); } private static void compareLocalTimeObjects() { LocalTime localTime1 = LocalTime.of(9, 10, 50); LocalTime localTime2 = LocalTime.of(9, 10, 50); LocalTime localTime3 = LocalTime.of(11, 45, 20); // compareTo() example if (localTime1.compareTo(localTime2) == 0) { System.out.println("localTime1 and localTime2 are equal"); } else { System.out.println("localTime1 and localTime2 are not equal"); } // isBefore() example if (localTime2.isBefore(localTime3)) { System.out.println("localTime2 comes before localTime3"); } // isAfter() example if (localTime3.isAfter(localTime1)) { System.out.println("localTime3 comes after localTime1"); } } }
Output:
localTime1 and localTime2 are equal localTime2 comes before localTime3 localTime3 comes after localTime1
Comments
Post a Comment