Compare Android Java dates only (excluding time)

When comparing dates and times in Java, I wanted to exclude times and compare only dates. Note that I wanted to compare "2018/04/06 12:15:27" and "2018/04/06 20:47:55" and judge only if it was the same day (excluding time).

It feels like a very muddy way, but for the time being, whether it's a timestamp or a Date class, just instantiate the Calendar class, set 0 to hours, minutes, seconds, and milliseconds, and compare with the compareTo () method of the Calendar class. is. Is there any smarter way (Java beginner's quibble)?

//00 from the time stamp of the appropriate date and time:00:00:Create 000 Calendar instances
int oneDayTimeStamp = 1523017440;
Calendar oneDayCal = Calendar.getInstance();
oneDayCal.setTimeInMillis(oneDayTimeStamp * 1000L);
//Set 0 to hours, minutes, seconds, and milliseconds
oneDayCal.set(Calendar.HOUR_OF_DAY, 0);
oneDayCal.set(Calendar.MINUTE, 0);
oneDayCal.set(Calendar.SECOND, 0);
oneDayCal.set(Calendar.MILLISECOND, 0);

//00 of the current date and time:00:00:Create 000 Calendar instances
Calendar now = Calendar.getInstance();
//Set 0 to hours, minutes, seconds, and milliseconds
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);

if (oneDayCal.compareTo(now) == 0) {
    //If it is 0, the date is the same
}

Thanks to @swordone for commenting, this is by far the smartest!

public int compareByDate (Calendar c1, Calendar c2) {
    int result = c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
    return (result != 0) ? result : c1.get(Calendar.DAY_OF_YEAR)- c2.get(Calendar.DAY_OF_YEAR);
}

This is the method I received from @Luice. I need to add a library, but I only need the truncatedCompareTo method. What the truncatedCompareTo method does inside is to execute the truncate method to set the hours, minutes, seconds, and milliseconds to 0, and then get the timestamp from the Calendar object and compare. I'd like to see the truncatedCompareTo method as an Android API. (What about Kotlin?)

// commons-lang3-3.7.Put the jar in the libs folder and build.Added the following description to gradle
compile files('libs/commons-lang3-3.7.jar') 
// Calendar : c1, Calendar : c2
if (DateUtils.truncatedCompareTo(c1, c2, Calendar.HOUR_OF_DAY) == 0) {
    //If it is 0, the date is the same
}

Recommended Posts

Compare Android Java dates only (excluding time)
[JAVA] Get only the file name, excluding the extension
[Java] Get miscellaneous dates
[Java] Date / time operations
Accurate time measurement (Java)
Compare Lists in Java