好的,我正式被这个难住了。我有一个 GregorianCalendar 对象,我想确定它是在过去、现在还是将来。到目前为止,Calendar#compareTo文档让我感到困惑,因为我得到了不稳定的结果。一个简单的测试类将说明我的问题:
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MyCal
{
public static void main( String[] args )
{
GregorianCalendar datePast = new GregorianCalendar();
datePast.add(Calendar.MONTH, -6); // subtract 6 months
GregorianCalendar datePresent = new GregorianCalendar();
GregorianCalendar dateFuture = new GregorianCalendar();
datePast.add(Calendar.MONTH, 6); // add 6 months
System.out.println("compare datePresent to datePast: "+datePresent.compareTo(datePast));
System.out.println("compare datePresent to datePresent: "+datePresent.compareTo(datePresent));
System.out.println("compare datePresent to dateFuture: "+datePresent.compareTo(dateFuture));
}
}
和输出:
compare datePresent to datePast: 1
compare datePresent to datePresent: 0
compare datePresent to dateFuture: 0
我对 compareTo 的理解是最后一行应该是-1。谁能告诉我我做错了什么?