我想有一个compareTo方法来忽略java.util.Date的时间部分。我想有很多方法可以解决这个问题。最简单的方法是什么?


当前回答

恐怕没有一种方法可以比较两个日期,可以称之为“容易”或“简单”。

当比较两个精度降低的时间实例时(例如,只是比较日期),你必须考虑时区对比较的影响。

例如,如果date1指定发生在+2时区的事件,而date2指定发生在EST时区的事件,则必须注意正确理解比较的含义。

你的目的是要弄清楚这两件事是否发生在各自时区的同一日历日期?或者,您是否需要知道这两个日期是否属于特定时区(例如,UTC或您的本地TZ)中的相同日历日期。

一旦你弄清楚你想要比较的是什么,就只需要在适当的时区获得年-月-日三元组合并进行比较。

Joda时间可能使实际的比较操作看起来更简洁,但是比较的语义仍然需要您自己弄清楚。

其他回答

这对我来说很管用:

var Date1 = new Date(dateObject1.toDateString()); //this sets time to 00:00:00
var Date2 = new Date(dateObject2.toDateString()); 
//do a normal compare
if(Date1 > Date2){ //do something }

我的建议:

    Calendar cal = Calendar.getInstance();
    cal.set(1999,10,01);   // nov 1st, 1999
    cal.set(Calendar.AM_PM,Calendar.AM);
    cal.set(Calendar.HOUR,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MILLISECOND,0);

    // date column in the Thought table is of type sql date
    Thought thought = thoughtDao.getThought(date, language);

    Assert.assertEquals(cal.getTime(), thought.getDate());

如果严格使用Date (java.util.Date),或者不使用任何外部库。用这个:

public Boolean compareDateWithoutTime(Date d1, Date d2) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    return sdf.format(d1).equals(sdf.format(d2));
}

如果你只想比较两个日期的月、日和年,下面的代码适用于我:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.format(date1).equals(sdf.format(date2));

谢谢抢劫。

`

SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy")

   Date date1=sdf.parse("03/25/2015");



  Date currentDate= sdf.parse(sdf.format(new Date()));

   return date1.compareTo(currentDate);

`