Java中Yearyearth類的compareTo()方法用於比較兩個YearMonth對象。它將這個YearMonth對象與作為參數傳遞給它的YearMonth對象進行比較。兩個YearMonth實例之間的比較首先是根據Year的值進行的,然後是對Month的比較。
用法:
public int compareTo(YearMonth otherYearMonth)
參數:此方法接受單個參數otherYearMonth,該參數是與此YearMonth進行比較的另一個YearMonth實例。
返回值:根據同位格返回一個整數比較器值:
- 如果Yearyear大於otherYearMonth,則返回1。
- 如果Yearyear小於otherYearMonth,則返回-1。
- 如果YearMonth等於otherYearMonth,則返回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::
// Programt 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-
相關用法
- Java YearMonth with()用法及代碼示例
- Java YearMonth atDay()用法及代碼示例
- Java YearMonth until()用法及代碼示例
- Java YearMonth getMonthValue()用法及代碼示例
- Java YearMonth getYear()用法及代碼示例
- Java YearMonth hashCode()用法及代碼示例
- Java YearMonth equals()用法及代碼示例
- Java YearMonth getMonth()用法及代碼示例
- Java YearMonth atEndOfMonth()用法及代碼示例
- Java YearMonth format()用法及代碼示例
- Java YearMonth isBefore()用法及代碼示例
- Java YearMonth isLeapYear()用法及代碼示例
- Java YearMonth lengthOfYear()用法及代碼示例
- Java YearMonth range()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 YearMonth compareTo() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。