Java中MonthDay類的compareTo()方法將此month-day與另一個month-day進行比較。
用法:
public int compareTo(MonthDay other)
參數:此方法接受參數other,該參數指定要比較的另一個month-day,並且不為null。
返回值:該函數返回比較器值。如果較小則為負,較大則為正。
異常:如果另一個為null,則該函數將引發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-
相關用法
- Java MonthDay from()用法及代碼示例
- Java MonthDay get()用法及代碼示例
- Java MonthDay with()用法及代碼示例
- Java MonthDay toString()用法及代碼示例
- Java MonthDay equals()用法及代碼示例
- Java MonthDay getDayOfMonth()用法及代碼示例
- Java MonthDay query()用法及代碼示例
- Java MonthDay atYear()用法及代碼示例
- Java MonthDay isValidYear()用法及代碼示例
- Java MonthDay isBefore()用法及代碼示例
- Java MonthDay adjustInto()用法及代碼示例
- Java MonthDay hashCode()用法及代碼示例
- Java MonthDay withDayOfMonth()用法及代碼示例
- Java MonthDay isAfter()用法及代碼示例
- Java MonthDay withMonth()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 MonthDay compareTo() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。