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


当前回答

Apache commons-lang几乎无处不在。那么这个呢?

if (DateUtils.isSameDay(date1, date2)) {
    // it's same
} else if (date1.before(date2)) {
   // it's before
} else {
   // it's after
}

其他回答

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

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

谢谢抢劫。

我不知道这是新的想法或其他,但我给你展示我所做的

SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date td_date = new Date();
String first_date = dtf.format(td_date);    //First seted in String 
String second_date = "30/11/2020";          //Second date you can set hear in String

String result = (first_date.equals(second_date)) ? "Yes, Its Equals":"No, It is not Equals";
System.out.println(result);

使用Java 8和Instant的另一个解决方案是使用truncatedTo方法

返回截断为指定单位的此即时的副本。

例子:

@Test
public void dateTruncate() throws InterruptedException {
    Instant now = Instant.now();
    Thread.sleep(1000*5);
    Instant later = Instant.now();
    assertThat(now, not(equalTo(later)));
    assertThat(now.truncatedTo(ChronoUnit.DAYS), equalTo(later.truncatedTo(ChronoUnit.DAYS)));
}

如果你只想比较两个没有时间的日期,那么下面的代码可能会帮助你:

final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date dLastUpdateDate = dateFormat.parse(20111116);
Date dCurrentDate = dateFormat.parse(dateFormat.format(new Date()));
if (dCurrentDate.after(dLastUpdateDate))
{
   add your logic
}

已经提到了apache common -utils:

org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.DAY_OF_MONTH)

给你Date对象,只包含日期,没有时间,你可以与Date. compareto进行比较