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


当前回答

如果你正在寻找一个简单的解决方案,但你不想从你的项目中更改已弃用的java.util.Date类,你可以将这个方法添加到你的项目中,并继续你的探索:

使用java.util.concurrent.TimeUnit

`

public boolean isSameDay(Date first, Date second) {
    long difference_In_Time = first.getTime() - second.getTime();
        // calculate difference in days
        long difference_In_Days = 
        TimeUnit
              .MILLISECONDS
              .toDays(difference_In_Time);
        if (difference_In_Days == 0) {
            return true;
        }
        return false;
    }

`

像这样实现它:

`

Date first = ...;
Date second = ...;
if (isSameDay(first, second)) {
    // congratulations, they are the same
}
else {
   // heads up champ, they are not the same
}

`

其他回答

只需结合YEAR属性检查DAY_OF_YEAR

boolean isSameDay = 
firstCal.get(Calendar.YEAR) == secondCal.get(Calendar.YEAR) &&
firstCal.get(Calendar.DAY_OF_YEAR) == secondCal.get(Calendar.DAY_OF_YEAR)

编辑:

现在我们可以使用Kotlin扩展函数的强大功能

fun Calendar.isSameDay(second: Calendar): Boolean {

    return this[Calendar.YEAR] == second[Calendar.YEAR] && this[Calendar.DAY_OF_YEAR] == second[Calendar.DAY_OF_YEAR]
}

fun Calendar.compareDatesOnly(other: Calendar): Int {

    return when {
        isSameDay(other) -> 0
        before(other) -> -1
        else -> 1
    }
}

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

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);

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

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

谢谢抢劫。

我更倾向于直接使用Joda库而不是java.util.Date,因为Joda区分了日期和时间(参见YearMonthDay和DateTime类)。

然而,如果你确实希望使用java.util.Date,我建议写一个实用方法;如。

public static Date setTimeToMidnight(Date date) {
    Calendar calendar = Calendar.getInstance();

    calendar.setTime( date );
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

使用http://mvnrepository.com/artifact/commons-lang/commons-lang

Date date1 = new Date();

Date date2 = new Date();

if (DateUtils.truncatedCompareTo(date1, date2, Calendar.DAY_OF_MONTH) == 0)
    // TRUE
else
    // FALSE