Java YearMonth compareTo()方法
Java中YearMonth类的compareTo()方法是用来比较两个YearMonth对象。它将这个YearMonth对象与作为参数传递给它的YearMonth对象进行比较。两个YearMonth实例之间的比较首先是根据Year的值进行的,然后是根据Month的值。
语法:
public int compareTo(YearMonth otherYearMonth)
参数 :该方法接受一个单一的参数 otherYearMonth ,它是要和这个YearMonth进行比较的另一个YearMonth实例。
返回值 : 它返回一个基于比较的积分比较器值。
- 如果这个YearMonth比otherYearMonth大,则返回1。
- 如果这个YearMonth小于otherYearMonth,则返回-1。
- 如果这个YearMonth等于其他YearMonth,则返回0。
以下程序说明了Java中YearMonth的compareTo()方法。
程序1 :
// Program to illustrate the compareTo() method
import java.util.*;
import java.time.*;
public class GfG {
public static void main(String[] args)
{
// Creates first YearMonth object
YearMonth firstYearMonth = YearMonth.of(2017, 8);
// Creates second YearMonth object
YearMonth secondYearMonth = YearMonth.of(2016, 11);
// compare the two YearMonth instances
System.out.println(firstYearMonth.compareTo(secondYearMonth));
}
}
输出
1
程序2 :
// Program to illustrate the compareTo() method
import java.util.*;
import java.time.*;
public class GfG {
public static void main(String[] args)
{
// Creates first YearMonth object
YearMonth firstYearMonth = YearMonth.of(2016, 11);
// Creates second YearMonth object
YearMonth secondYearMonth = YearMonth.of(2016, 11);
// compare the two YearMonth instances
System.out.println(firstYearMonth.compareTo(secondYearMonth));
}
}
输出
0
参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#compareTo-java.time.YearMonth-