java.util.Calendar compareTo()方法

java.util.Calendar.compareTo() 方法比较两个日历对象之间的时间值(毫秒偏移量)。

1 语法

public int compareTo(Calendar anotherCalendar)  

2 参数

anotherCalendar:要比较的Calendar对象。

3 返回值

返回0,1或-1的整数值

4 示例1 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.Calendar compareTo()方法的例子
 */
import java.util.Calendar;  
public class CalendarComparetoExample1 {      
public static void main(String[] args) {  
      // create two calendar at the different dates  
        Calendar cal1 =  (Calendar) Calendar.getInstance();  
      Calendar cal2 = (Calendar) Calendar.getInstance();;  
      // compare the time values represented by two calendar objects.  
       cal2.add(Calendar.HOUR, 10);  
       cal2.add(Calendar.MINUTE, 10);  
       cal2.add(Calendar.SECOND, 10);  
      int i = cal2.compareTo(cal1);  
       // It should return a positive integer(usually 1),  
      //if the current triggering object is greater than the passed one  
      System.out.println("The result is :"+i);        
   }  
} 

输出结果为:

The result is :1

5 示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.Calendar compareTo()方法的例子
 */
import java.util.Calendar;  
public class CalendarComparetoExample2 {  
    public static void main(String[] args) {  
      // create two calendar at the different dates  
       Calendar cal1 =  (Calendar) Calendar.getInstance();  
      Calendar cal2 = (Calendar) Calendar.getInstance();;  
      // compare the time values represented by two calendar objects.  
       cal2.add(Calendar.HOUR, 10);  
       cal2.add(Calendar.MINUTE, 10);  
       cal2.add(Calendar.SECOND, 10);  
       int z = cal1.compareTo(cal2);  
      // It should return a negative integer( -1),  
      //if the current triggering object is less than the passed one  
      System.out.println("The result is :" + z);  
   }  
}  

输出结果为:

The result is :-1

6 示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.Calendar compareTo()方法的例子
 */
import java.util.Calendar;  
public class CalendarComparetoExample3 {     
public static void main(String[] args) {  
      // create two calendar at the different dates  
       Calendar cal1 =  (Calendar) Calendar.getInstance();  
     Calendar cal2 = (Calendar) Calendar.getInstance();;  
      // compare the time values represented by two calendar objects.  
       cal2.add(Calendar.HOUR, 10);  
       cal2.add(Calendar.MINUTE, 10);  
       cal2.add(Calendar.SECOND, 10);  
      // compare again but with the two calendars swapped  
      int j = cal1.compareTo(cal1);  
      // It should return 0 ,  
      //if the current triggering object is less equal to the  passed one  
      System.out.println("The result is :" + j);  
      }  
} 

输出结果为:

The result is :0

 

热门文章

优秀文章