2011-08-16 314 views
0

我有两个日期,我想对它们进行比较。我记录了实际的日期,以确保它的正确性。Date compareTo()方法总是返回-1

Date photoDate = new Date(mPhotoObject.calendar.getTimeInMillis()); 

SimpleDateFormat dateFormat = new SimpleDateFormat("M.d.yy"); 


Log.v("photo date is", dateFormat.format(photoDate)); 
Date currentDate = new Date(Calendar.getInstance().getTimeInMillis()); 
Log.v("current date is", dateFormat.format(currentDate)); 
Log.v("date comparison", photoDate.compareTo(currentDate)+""); 

if(photoDate.compareTo(currentDate)<0) { 
    view.showFooButton(false); 
    } else { 
    view.showFooButton(true); 
    } 

出于某种原因,compareTo方法总是返回-1即使这个日期是日期参数之前

+0

参见:http://stackoverflow.com/questions/1439779/how-to-compare-two-日期 - 没有时间部分 – Vlad

回答

2

Date包括时间缩短到毫秒。您需要可以使用不同的比较或修剪的时间信息:

final long millisPerDay= 24 * 60 * 60 * 1000; 
... 
Date photoDate = new Date((long)Math.floor(mPhotoObject.calendar.getTimeInMillis()/millisPerDay) * millisPerDay); 
... 
Date currentDate = new Date((long)Math.floor(Calendar.getInstance().getTimeInMillis()/millisPerDay) * millisPerDay); 
+0

谢谢,弗拉德。我很感激。我尝试过,但它似乎没有工作。也许是因为我不得不将它转换为int(即使它被声明为int) – LuxuryMode

+0

@LuxuryMode:实际上它需要转换为long,因为Math.floor()返回double。更新。 – Vlad

+0

工作就像一个魅力。谢谢你,先生。 – LuxuryMode

1

这是预期的行为,如果参数在日期之后,则返回-1。

Date compareTo

+0

对不起,我的意思是相反的。 ;)我编辑了我的问题。 – LuxuryMode

0

另一种解决方案是,因为你只希望有一天&年相比,一个月,你应该创建其他日期的克隆,并设置根据你需要的日,月,年

Date date=new Date(otherDate.getTime()); 
date.setDate(...); 
date.setMonth(...); 
date.setYear(...); 

然后用比较。

使用比较两个日期的例子功能只有他们的一天,一个月,一年是:

public static int compareDatesOnly(final Date date1, final Date date2) { 
    final Date dateToCompare = new Date(date1.getTime()); 
    dateToCompare.setDate(date2.getDate()); 
    dateToCompare.setMonth(date2.getMonth()); 
    dateToCompare.setYear(date2.getYear()); 
    return date1.compareTo(dateToCompare); 
}