public class time implements compareTo<Date> 报错
{
Date a=new Date(2012,1,1);
Date b=new Date(2012,5,5);

a.compareTo(b);

}
我初学java几天,各种接口不熟悉,上面是胡写的。查看了API,Date中有 compareTo(Date anotherDate)   比较两个日期的顺序。返回值是int想问下:这个compareTo 到底怎么用?是有现成的比较date的,还是得重写?如果需要重写,请大家帮忙写几行吧。我真没写过另外,返回值是int ,是不是 返回0就是相等?  返回大于1的是参数中的日期大(晚)还是?

解决方案 »

  1.   

    a.after(b) 或者 a.before(b) 返回boolean
      

  2.   

    有个方法是返回long的一个数值,是从1970开始的毫秒数
    用这两个数来比较就可以了
    要想知道差多长时间,就把这个毫秒数一减,然后换算成你要的时分秒就可以了
      

  3.   

    public static void main(String[] args){
    System.out.println(comt("2011-06-23","2012-06-23"));
    }

    public static int comt(String a,String b){
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    try {
    Date d1=sdf.parse(a);
    Date d2=sdf.parse(b);
    if(d1.getTime()>d2.getTime())
    {
    return 1;
    }
    else{
    return 0;
    }
    } catch (ParseException e) { e.printStackTrace();
    }
    return 0;
    }
    看哈应该就懂了.
      

  4.   


    public class Bijiao {
    public static void main(String[] args) {
    System.out.println(comt("2011-06-23", "2012-06-23"));
    } public static int comt(String a, String b) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
    Date d1 = sdf.parse(a);
    Date d2 = sdf.parse(b);
    if (d1.getTime() > d2.getTime()) {
    return 1;
    } else {
    if (d1.getTime() < d2.getTime()) {
    return -1;
    } else {
    return 0;
    }
    }
    } catch (Exception e) { e.printStackTrace();
    }
    return 0;
    }
    }