当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Calendar compareTo()用法及代码示例


Calendar类的add(Calendar Calendar2)方法用于将此Calendar对象的时间值或毫秒偏移与传递的Calendar对象进行比较。

用法:

public int compareTo(Calendar Calendar2)

参数:该方法采用Calendar对象类型的一个参数Calendar2,表示要与该Calendar对象进行比较的对象。


返回值:该方法返回一个整数值,并且可以返回以下任意一项:

  1. 如果传递的参数等于此Calendar对象,则该方法返回0。
  2. 如果此Calendar对象的时间大于传递的对象,则该方法返回1。
  3. 如果此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)



相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 Calendar compareTo() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。