Calendar類的add(Calendar Calendar2)方法用於將此Calendar對象的時間值或毫秒偏移與傳遞的Calendar對象進行比較。
用法:
public int compareTo(Calendar Calendar2)
參數:該方法采用Calendar對象類型的一個參數Calendar2,表示要與該Calendar對象進行比較的對象。
返回值:該方法返回一個整數值,並且可以返回以下任意一項:
- 如果傳遞的參數等於此Calendar對象,則該方法返回0。
- 如果此Calendar對象的時間大於傳遞的對象,則該方法返回1。
- 如果此Calendar對象的時間小於傳遞的對象,則該方法返回-1。
以下示例程序旨在說明Calendar類的compareTo()方法的用法:
示例1:
// Java Code to illustrate compareTo() Method
import java.util.*;
public class CalendarClassDemo {
public static void main(String args[])
{
// Creating a calendar object
Calendar calndr1
= Calendar.getInstance();
// Creating another calendar object
Calendar calndr2
= new GregorianCalendar(2018, 12, 2);
// Comparing the time
int val = calndr1.compareTo(calndr2);
// Displaying the result of comparison
System.out.println("First"
+ " comparison result is: "
+ val);
// Comparing the time
val = calndr2.compareTo(calndr1);
// Displaying the result of comparison
System.out.println("Second"
+ " comparison result is: "
+ val);
}
}
輸出:
First comparison result is: 1 Second comparison result is: -1
示例2:
// Java Code to illustrate compareTo() Method
import java.util.*;
public class CalendarClassDemo {
public static void main(String args[])
{
// Creating a calendar object
Calendar calndr1 = Calendar.getInstance();
// Creating another calendar object
Calendar calndr2 = Calendar.getInstance();
// Comparing the time
int val = calndr1.compareTo(calndr2);
// Displaying the result of comparison
System.out.println("The"
+ " comparison result is: "
+ val);
}
}
輸出:
The comparison result is: -1
參考: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#compareTo(java.util.Calendar)
相關用法
- Java ChronoLocalDate compareTo()用法及代碼示例
- Java Instant compareTo()用法及代碼示例
- Java ChronoZonedDateTime compareTo()用法及代碼示例
- Java Short compareTo()用法及代碼示例
- Java Byte compareTo()用法及代碼示例
- Java LocalTime compareTo()用法及代碼示例
- Java Date compareTo()用法及代碼示例
- Java ShortBuffer compareTo用法及代碼示例
- Java Year compareTo()用法及代碼示例
- Java UUID compareTo()用法及代碼示例
- Java DoubleBuffer compareTo()用法及代碼示例
- Java MonthDay compareTo()用法及代碼示例
- Java OffsetDateTime compareTo()用法及代碼示例
- Java Path compareTo()用法及代碼示例
- Java Charset compareTo()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Calendar compareTo() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。