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