LocalDate类compareTo()方法 (LocalDate Class compareTo() method)
compareTo() method is available in java.time package.
compareTo()方法在java.time包中可用。
compareTo() method is used to compare this LocalDate object to the given object.
compareTo()方法用于将此LocalDate对象与给定对象进行比较。
compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
compareTo()方法是一种非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
compareTo() method does not throw an exception at the time of comparing.
compareTo()方法在比较时不会引发异常。
Syntax:
句法:
public int compareTo(ChronoLocalDate l_date);
Parameter(s):
参数:
ChronoLocalDate l_date – represents the object to be compared to this LocalDate.
ChronoLocalDate l_date –表示要与此LocalDate比较的对象。
Return value:
返回值:
The return type of this method is int, it may return anyone of the given values,
此方法的返回类型为int ,它可以返回任何给定值,
When (this LocalDate) < (ChronoLocalDate l_date), it returns -ve.
当(this LocalDate)<(ChronoLocalDate l_date)时,它返回-ve。
When (this LocalDate) > (ChronoLocalDate l_date), it returns +ve.
当(this LocalDate)>(ChronoLocalDate l_date)时,它返回+ ve。
When (this LocalDate) == (ChronoLocalDate l_date), it returns 0.
当(this LocalDate)==(ChronoLocalDate l_date)时,它返回0。
Example:
例:
// Java program to demonstrate the example
// of int compareTo(ChronoLocalDate l_date)
// method of LocalDate
import java.time.*;
public class CompareToOfLocalDate {
public static void main(String args[]) {
// Instantiates two LocalDate
LocalDate l_da1 = LocalDate.parse("2007-04-04");
LocalDate l_da2 = LocalDate.now();
// Display l_da1,l_da2
System.out.println("LocalDate l_da1 and l_da2: ");
System.out.println("l_da1: " + l_da1);
System.out.println("l_da2: " + l_da2);
System.out.println();
// Here, this method compares this date object to
// the given date object i.e. it returns -ve
// value because l_da1 = 2007-04-04 and l_da2
// = 2020-05-08 so l_da1 - l_da2 = 2007-2020
// i.e. -13 will be returned
int compare = l_da1.compareTo(l_da2);
// Display compare
System.out.println("l_da1.compareTo(l_da2): " + compare);
// Here, this method compares this date object to
// the given date object i.e. it returns +ve
// value because l_da1 = 2007-04-04 and l_da2
// = 2020-05-08 so l_da2 - l_da1 = 2020-2007
// i.e. 13 will be returned
compare = l_da2.compareTo(l_da1);
// Display compare
System.out.println("l_da2.compareTo(l_da1): " + compare);
// Here, this method compares this date object to
// the given date object i.e. it returns 0
// because l_da1 == l_da1
compare = l_da1.compareTo(l_da1);
// Display compare
System.out.println("l_da1.compareTo(l_da1): " + compare);
}
}
Output
输出量
LocalDate l_da1 and l_da2:
l_da1: 2007-04-04
l_da2: 2020-05-29l_da1.compareTo(l_da2): -13
l_da2.compareTo(l_da1): 13
l_da1.compareTo(l_da1): 0
翻译自: https://www.includehelp.com/java/localdate-compareto-method-with-example.aspx