Android 开发笔记 “java.util.Calendar.compareTo()”

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

声明

以下是java.util.Calendar.compareTo()方法的声明

public int compareTo(Calendar anotherCalendar)

参数

  • anotherCalendar -- 要比较的Calendar对象。

返回值

如果参数所代表的时间等于通过此Calendar对象表示的时间方法返回0;或如果此Calendar的时间是由参数表示的时间之前返回小于0值,或如果该日历的时间所表示的时间之后返回大于0值。

异常

  • NullPointerException - 如果指定的Calendar为null。

  • IllegalArgumentException - 如果不能得到指定的日历Calendar 对象的时间值

例子

下面的示例演示java.util.calendar.compareTo()方法的用法。

package com.yiibai;

import java.util.*;

public class CalendarDemo {

   public static void main(String[] args) {

      // create two calendar at the different dates
      Calendar cal1 = new GregorianCalendar(2015, 8, 15);
      Calendar cal2 = new GregorianCalendar(2008, 1, 02);

      // compare the time values represented by two calendar objects.
      int i = cal1.compareTo(cal2);

      // return positive value if equals else return negative value
      System.out.println("The result is :"+i);

      // compare again but with the two calendars swapped
      int j = cal2.compareTo(cal);

      // return positive value if equals else return negative value
      System.out.println("The result is :" + j);

   }
}

让我们来编译和运行上面的程序,这将产生以下结果:

The result is :1
The result is :-1
原文地址:https://www.cnblogs.com/Dylanblogs/p/4222495.html