LocalDate compareTo()方法
在 Java 中的 LocalDate 类中,可以使用 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("
The first LocalDate object is greater than the second LocalDate object"); else if(val < 0) System.out.println("
The first LocalDate object is lesser than the second LocalDate object"); else System.out.println("
The 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() 方法对其进行比较,并使用 if else 语句显示结果。演示此操作的代码片段如下所示 −
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("
The first LocalDate object is greater than the second LocalDate object"); else if(val < 0) System.out.println("
The first LocalDate object is lesser than the second LocalDate object"); else System.out.println("
The LocalDate objects are equal");
广告