Java教程

Java Calendar compareTo()方法

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

语法

public int compareTo(Calendar anotherCalendar)

参数

anotherCalendar-要比较的Calendar对象。

返回

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

抛出

NullPointerException -如果指定的Calendar为null。
IllegalArgumentException -如果无法获取指定Calendar对象的时间值

示例1

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

示例2

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

示例3

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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4