Compare dates ignoring milliseconds?

Viewed 19134

Is there a way to compare two calendar objects, but ignore milliseconds?

I have written a test case that compared two calendar objects, but there is a problem. Although all of the day, month, minutes and hours match, the milliseconds doesn't matches. I get the expected date before getting the real date:

/**
 * @return
 */
private Calendar getExpectedOneMonthDateFromCurrentDate() {
    Calendar expectedOneMonth = Calendar.getInstance();
    expectedOneMonth.add(Calendar.MONTH, -1);
    return expectedOneMonth;
}

assertEquals(getExpectedOneMonthDateFromCurrentDate(),
             DateRange.LAST_ONE_MONTH.getToDate());
11 Answers

If you are on Java 8, you can use the Java Time API, specifically Calendar::toInstant(), followed by Instant::truncatedTo(). Specify the granularity of truncation using ChronoUnit enum.

myCalendar.toInstant().truncatedTo( ChronoUnit.SECONDS )  // Lop off any fractional second.

Example.

    Calendar oneMonthIsh = Calendar.getInstance();
    oneMonthIsh.add(Calendar.MONTH, -1);
    oneMonthIsh.add(Calendar.MINUTE, 1);

    assertNotEquals(oneMonthIsh.toInstant(), getExpectedOneMonthDateFromCurrentDate());
    assertEquals(oneMonthIsh.toInstant().truncatedTo(ChronoUnit.DAYS),getExpectedOneMonthDateFromCurrentDate().toInstant()
    .truncatedTo(ChronoUnit.DAYS));

If you use jodaTime, the setCopy("0") method returns a DateTime object with milliseconds set to 0 to make it easy to compare:

DateTime dateTimeZerodMillis = new DateTime().millisOfSecond ().setCopy("0")

Though I am way too late for the party, sharing my simple alternate approach for posterity

Two date objects comparision by ignoring the milliseconds using org.apache.commons.lang3.time.DateUtils

Date date1 = new Date(1503055069000L);
Date date2 = new Date(1503055069683L);
//Here the two dates are differed by 683 milliseconds, if we want to skip just the 
//683 milliseconds difference then we can use the below logic
if(DateUtils.setMilliseconds(date1, 0).equals(DateUtils.setMilliseconds(date2, 0))){
    //your business process
  
}

NOTE: DateUtils#setMilliseconds method sets the milliseconds field to a date returning a new object. The original Date is unchanged. so until you are reassigning the object reference the original date object values are unchanged.

Related