我有两个日期,我想比较它们。我已经记录了实际日期以确保其正确性。
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,即使此日期不早于 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);
关于java - DatecompareTo() 方法总是返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7084310/