可以使用compareTo()
Java中LocalTime类中的方法比较两个LocalTime对象。此方法需要单个参数,即要比较的LocalTime对象。
如果第一个LocalTime对象大于第二个LocalTime对象,则返回正数;如果第一个LocalTime对象小于第二个LocalTime对象,则返回负数;如果两个LocalTime对象相等,则返回零。
演示此程序如下
import java.time.*; public class Main{ public static void main(String[] args){ LocalTime lt1 = LocalTime.parse("11:37:12"); LocalTime lt2 = LocalTime.parse("23:15:30"); System.out.println("The first LocalTime object is: " + lt1); System.out.println("The second LocalTime object is: " + lt2); int val = lt1.compareTo(lt2); if(val > 0) System.out.println("\nThe first LocalTime object is greater than the second LocalTimeobject"); else if(val < 0) System.out.println("\nThe first LocalTime object is lesser than the second LocalTimeobject"); else System.out.println("\nThe LocalTime objects are equal"); } }
The first LocalTime object is: 11:37:12 The second LocalTime object is: 23:15:30 The first LocalTime object is lesser than the second LocalTime object
现在让我们了解上面的程序。
首先,显示两个LocalTime对象。然后使用compareTo()
方法比较它们,并使用if else语句显示结果。演示此代码段如下所示:
LocalTime lt1 = LocalTime.parse("11:37:12"); LocalTime lt2 = LocalTime.parse("23:15:30"); System.out.println("The first LocalTime object is: " + lt1); System.out.println("The second LocalTime object is: " + lt2); int val = lt1.compareTo(lt2); if(val > 0) System.out.println("\nThe first LocalTime object is greater than the second LocalTimeobject"); else if(val < 0) System.out.println("\nThe first LocalTime object is lesser than the second LocalTimeobject"); else System.out.println("\nThe LocalTime objects are equal");