使用方法 `compareTo()` 和 `equals()` 没有得到预期的结果

dont get expected result using method `compareTo()` and `equals()`

我需要比较两个日期。 我从我的数据库中读取了其中一个,它的类型是 String。所以首先我以我需要的特定格式将 String 转换为 Date,然后我再次以我想要的格式从系统中获取第二个 Date。 我的问题是,即使它们相同,我也会得到意想不到的结果。

我的代码是:

public class SaharDateComparerActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sahar_date_comparer);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    String dateString ="18/02/2015";


    Date datee = convertStringToDate(dateString);
    Log.i("SAHAR","date 1:  "+ dateFormat.format(datee).toString());


    Date myDate = new Date();
    Log.i("SAHAR", "date 2:  "+dateFormat.format(myDate).toString());

    int testttt=    datee.compareTo(myDate);
    boolean a = datee.toString().equals(myDate.toString());
    Log.i("SAHAR", "date compared:  "+String.valueOf(testttt));
    Log.i("SAHAR", "date equal:  "+String.valueOf(a));

}

public Date convertStringToDate(String strDate) {
    // String startDateString = "06/27/2007";
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date date = null;
    try {
        date = df.parse(strDate);
        String newDateString = df.format(date);
        System.out.println(newDateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
 }
}

如您所见,我的两个日期相同,但是当我使用 compareTo() 时我得到 -1,而当我使用 equals() 方法时我得到 -1!

这是因为这两个日期有不同的时、分、秒,...(你看不到什么时候你只做 toString() 输出)

您可以删除它们:Compare two dates in Java

或者您制作自己的 Comperator,只需检查 day/month/year。

您应该在清除来自数据库的日期中缺少的时间单位后比较您的 Date 对象,即没有小时、分钟、秒等。这会影响您的结果。

String dateString ="18/02/2015";
Date datee = convertStringToDate(dateString);

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

Log.i("SAHAR", "Comparison result: " + datee.equals(c.getTime()));