Java MonthDay compareTo()方法及示例

来源:这里教程网 时间:2026-02-17 20:58:58 作者:

Java MonthDay compareTo()方法及示例

Java中MonthDay类的 compareTo() 方法将这个月日与另一个月日进行比较。

语法

public int compareTo(MonthDay other)

参数。该方法接受一个参数other,指定与之比较的另一个月日,且不为空。

返回: 该函数返回 比较器的值 如果它是小的,它可以是负的,如果它是大的,它可以是正的。

异常 :如果其他参数为空,函数会抛出一个 NullPointerException

以下程序说明了 MonthDay.compareTo() 方法。

程序1 :

// Program to illustrate the compareTo() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        MonthDay tm1 = MonthDay.parse("--12-06");          // Uses the function        LocalDate dt1 = tm1.atYear(2018);          // Parses the date        MonthDay tm2 = MonthDay.parse("--12-06");          // Uses the function        LocalDate dt2 = tm2.atYear(2018);          // Prints the date        System.out.println(dt1.compareTo(dt2));    }}

输出。

0

程序2

// Program to illustrate the compareTo() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        MonthDay tm1 = MonthDay.parse("--10-06");          // Uses the function        LocalDate dt1 = tm1.atYear(2018);          // Parses the date        MonthDay tm2 = MonthDay.parse("--12-06");          // Uses the function        LocalDate dt2 = tm2.atYear(2018);          // Prints the date        System.out.println(dt1.compareTo(dt2));    }}

输出。

-2

程序3

// Program to illustrate the compareTo() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        MonthDay tm1 = MonthDay.parse("--10-06");          // Uses the function        LocalDate dt1 = tm1.atYear(2018);          // Parses the date        MonthDay tm2 = MonthDay.parse("--09-06");          // Uses the function        LocalDate dt2 = tm2.atYear(2018);          // Prints the date        System.out.println(dt1.compareTo(dt2));    }}

输出。

1

参考资料: https://docs.oracle.com/javase/8/docs/api/java/time/MonthDay.html#compareTo-java.time.MonthDay-

相关推荐