📜  Java中的 YearMonth compareTo() 方法

📅  最后修改于: 2022-05-13 01:55:48.523000             🧑  作者: Mango

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。
  • 它返回 0 是这个 YearMonth 等于 otherYearMonth。

下面的程序说明了Java中 YearMonth 的 compareTo() 方法:

程序 1

Java
// 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));
    }
}


Java
// 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));
    }
}


输出:
1

方案二

Java

// 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: Java/time/YearMonth.html#compareTo-java.time.YearMonth-