Compare Date objects with different levels of precision

JavaJunit

Java Problem Overview


I have a JUnit test that fails because the milliseconds are different. In this case I don't care about the milliseconds. How can I change the precision of the assert to ignore milliseconds (or any precision I would like it set to)?

Example of a failing assert that I would like to pass:

Date dateOne = new Date();
dateOne.setTime(61202516585000L);
Date dateTwo = new Date();
dateTwo.setTime(61202516585123L);
assertEquals(dateOne, dateTwo);

Java Solutions


Solution 1 - Java

There are libraries that help with this:

Apache commons-lang

If you have Apache commons-lang on your classpath, you can use DateUtils.truncate to truncate the dates to some field.

assertEquals(DateUtils.truncate(date1,Calendar.SECOND),
             DateUtils.truncate(date2,Calendar.SECOND));

There is a shorthand for this:

assertTrue(DateUtils.truncatedEquals(date1,date2,Calendar.SECOND));

Note that 12:00:00.001 and 11:59:00.999 would truncate to different values, so this might not be ideal. For that, there is round:

assertEquals(DateUtils.round(date1,Calendar.SECOND),
             DateUtils.round(date2,Calendar.SECOND));

AssertJ

Starting with version 3.7.0, AssertJ added an isCloseTo assertions, if you are using the Java 8 Date / Time API.

LocalTime _07_10 = LocalTime.of(7, 10);
LocalTime _07_42 = LocalTime.of(7, 42);
assertThat(_07_10).isCloseTo(_07_42, within(1, ChronoUnit.HOURS));
assertThat(_07_10).isCloseTo(_07_42, within(32, ChronoUnit.MINUTES));

It also works with legacy java Dates as well:

Date d1 = new Date();
Date d2 = new Date();
assertThat(d1).isCloseTo(d2, within(100, ChronoUnit.MILLIS).getValue());

Solution 2 - Java

Yet another workaround, I'd do it like this:

assertTrue("Dates aren't close enough to each other!", (date2.getTime() - date1.getTime()) < 1000);

Solution 3 - Java

Use a DateFormat object with a format that shows only the parts you want to match and do an assertEquals() on the resulting Strings. You can also easily wrap that in your own assertDatesAlmostEqual() method.

Solution 4 - Java

You could do something like this:

assertTrue((date1.getTime()/1000) == (date2.getTime()/1000));

No String comparisons needed.

Solution 5 - Java

In JUnit you can program two assert methods, like this:

public class MyTest {
  @Test
  public void test() {
    ...
    assertEqualDates(expectedDateObject, resultDate);

    // somewhat more confortable:
    assertEqualDates("01/01/2012", anotherResultDate);
  }

  private static final String DATE_PATTERN = "dd/MM/yyyy";

  private static void assertEqualDates(String expected, Date value) {
      DateFormat formatter = new SimpleDateFormat(DATE_PATTERN);
      String strValue = formatter.format(value);
      assertEquals(expected, strValue);
  }

  private static void assertEqualDates(Date expected, Date value) {
    DateFormat formatter = new SimpleDateFormat(DATE_PATTERN);
    String strExpected = formatter.format(expected);
    String strValue = formatter.format(value);
    assertEquals(strExpected, strValue);
  }
}

Solution 6 - Java

You can chose which precision level you want when comparing dates, e.g.:

LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
// e.g. in MySQL db "timestamp" is without fractional seconds precision (just up to seconds precision)
assertEquals(myTimestamp, now);

Solution 7 - Java

I don't know if there is support in JUnit, but one way to do it:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Example {

    private static SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");

    private static boolean assertEqualDates(Date date1, Date date2) {
        String d1 = formatter.format(date1);            
        String d2 = formatter.format(date2);            
        return d1.equals(d2);
    }    

    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = new Date();

        if (assertEqualDates(date1,date2)) { System.out.println("true!"); }
    }
}

Solution 8 - Java

With AssertJ you could provide a custom comparator what is especially handy if you are comparing entire object structures and not single values so that other methods like isEqualToIgnoringMillis or isCloseTo are not practical.

assertThat(thing)
  .usingRecursiveComparison()
  .withComparatorForType(
      (a, b) -> a.truncatedTo(ChronoUnit.MILLIS).compareTo(b.truncatedTo(ChronoUnit.MILLIS)),
      OffsetDateTime.class
  )

Solution 9 - Java

This is actually a harder problem than it appears because of the boundary cases where the variance that you don't care about crosses a threshold for a value you are checking. e.g. the millisecond difference is less than a second but the two timestamps cross the second threshold, or the minute threshold, or the hour threshold. This makes any DateFormat approach inherently error-prone.

Instead, I would suggest comparing the actual millisecond timestamps and provide a variance delta indicating what you consider an acceptable difference between the two date objects. An overly verbose example follows:

public static void assertDateSimilar(Date expected, Date actual, long allowableVariance)
{
    long variance = Math.abs(allowableVariance);

    long millis = expected.getTime();
    long lowerBound = millis - allowableVariance;
    long upperBound = millis + allowableVariance;

    DateFormat df = DateFormat.getDateTimeInstance();

    boolean within = lowerBound <= actual.getTime() && actual.getTime() <= upperBound;
    assertTrue(MessageFormat.format("Expected {0} with variance of {1} but received {2}", df.format(expected), allowableVariance, df.format(actual)), within);
}

Solution 10 - Java

Using JUnit 4 you could also implement a matcher for testing dates according to your chosen precision. In this example the matcher takes a string format expression as a parameter. The code is not any shorter for this example. However the matcher class may be reused; and if you give it a describing name you can document the intention with the test in an elegant way.

import static org.junit.Assert.assertThat;
// further imports from org.junit. and org.hamcrest.

@Test
public void testAddEventsToBaby() {
    Date referenceDate = new Date();
    // Do something..
    Date testDate = new Date();
    
    //assertThat(referenceDate, equalTo(testDate)); // Test on equal could fail; it is a race condition
    assertThat(referenceDate, sameCalendarDay(testDate, "yyyy MM dd"));
}

public static Matcher<Date> sameCalendarDay(final Object testValue, final String dateFormat){

    final SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    
    return new BaseMatcher<Date>() {

        protected Object theTestValue = testValue;


        public boolean matches(Object theExpected) {
            return formatter.format(theExpected).equals(formatter.format(theTestValue));
        }

        public void describeTo(Description description) {
            description.appendText(theTestValue.toString());
        }
    };
}

Solution 11 - Java

use AssertJ assertions for Joda-Time (http://joel-costigliola.github.io/assertj/assertj-joda-time.html)

import static org.assertj.jodatime.api.Assertions.assertThat;
import org.joda.time.DateTime;

assertThat(new DateTime(dateOne.getTime())).isEqualToIgnoringMillis(new DateTime(dateTwo.getTime()));

the test failing message is more readable

java.lang.AssertionError: 
Expecting:
  <2014-07-28T08:00:00.000+08:00>
to have same year, month, day, hour, minute and second as:
  <2014-07-28T08:10:00.000+08:00>
but had not.

Solution 12 - Java

Just compare the date parts you're interested in comparing:

Date dateOne = new Date();
dateOne.setTime(61202516585000L);
Date dateTwo = new Date();
dateTwo.setTime(61202516585123L);

assertEquals(dateOne.getMonth(), dateTwo.getMonth());
assertEquals(dateOne.getDate(), dateTwo.getDate());
assertEquals(dateOne.getYear(), dateTwo.getYear());

// alternative to testing with deprecated methods in Date class
Calendar calOne = Calendar.getInstance();
Calendar calTwo = Calendar.getInstance();
calOne.setTime(dateOne);
calTwo.setTime(dateTwo);

assertEquals(calOne.get(Calendar.MONTH), calTwo.get(Calendar.MONTH));
assertEquals(calOne.get(Calendar.DATE), calTwo.get(Calendar.DATE));
assertEquals(calOne.get(Calendar.YEAR), calTwo.get(Calendar.YEAR));

Solution 13 - Java

If you were using Joda you could use Fest Joda Time.

Solution 14 - Java

JUnit has a built in assertion for comparing doubles, and specifying how close they need to be. In this case, the delta is within how many milliseconds you consider dates equivalent. This solution has no boundary conditions, measures absolute variance, can easily specify precision, and requires no additional libraries or code to be written.

    Date dateOne = new Date();
    dateOne.setTime(61202516585000L);
    Date dateTwo = new Date();
    dateTwo.setTime(61202516585123L);
    // this line passes correctly 
    Assert.assertEquals(dateOne.getTime(), dateTwo.getTime(), 500.0);
    // this line fails correctly
    Assert.assertEquals(dateOne.getTime(), dateTwo.getTime(), 100.0);

Note It must be 100.0 instead of 100 (or a cast to double is needed) to force it to compare them as doubles.

Solution 15 - Java

Something like this might work:

assertEquals(new SimpleDateFormat("dd MMM yyyy").format(dateOne),
                   new SimpleDateFormat("dd MMM yyyy").format(dateTwo));

Solution 16 - Java

Instead of using new Date directly, you can create a small collaborator, which you can mock out in your test:

public class DateBuilder {
    public java.util.Date now() {
        return new java.util.Date();
    }
}

Create a DateBuilder member and change calls from new Date to dateBuilder.now()

import java.util.Date;

public class Demo {

    DateBuilder dateBuilder = new DateBuilder();

    public void run() throws InterruptedException {
        Date dateOne = dateBuilder.now();
        Thread.sleep(10);
        Date dateTwo = dateBuilder.now();
        System.out.println("Dates are the same: " + dateOne.equals(dateTwo));
    }

    public static void main(String[] args) throws InterruptedException {
        new Demo().run();
    }
}

The main method will produce:

Dates are the same: false

In the test you can inject a stub of DateBuilder and let it return any value you like. For example with Mockito or an anonymous class which overrides now():

public class DemoTest {
    
    @org.junit.Test
    public void testMockito() throws Exception {
        DateBuilder stub = org.mockito.Mockito.mock(DateBuilder.class);
        org.mockito.Mockito.when(stub.now()).thenReturn(new java.util.Date(42));
        
        Demo demo = new Demo();
        demo.dateBuilder = stub;
        demo.run();
    }

    @org.junit.Test
    public void testAnonymousClass() throws Exception {
        Demo demo = new Demo();
        demo.dateBuilder = new DateBuilder() {
            @Override
            public Date now() {
                return new Date(42);
            }
        };
        demo.run();
    }
}

Solution 17 - Java

Convert the dates to String using SimpleDateFromat, specify in the constructor the required date/time fields and compare the string values:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String expectedDate = formatter.format(dateOne));
String dateToTest = formatter.format(dateTwo);
assertEquals(expectedDate, dateToTest);

Solution 18 - Java

I did a small class that might be useful for some googlers that end up here : https://stackoverflow.com/a/37168645/5930242

Solution 19 - Java

Here is a utility function that did the job for me.

    private boolean isEqual(Date d1, Date d2){
        return d1.toLocalDate().equals(d2.toLocalDate());
    }

Solution 20 - Java

You can use isEqualToIgnoringSeconds method to ignore seconds and compare only by minutes:

Date d1 = new Date();
Thread.sleep(10000);
Date d2 = new Date();
assertThat(d1).isEqualToIgnoringSeconds(d2); // true

Solution 21 - Java

i cast the objects to java.util.Date and compare

assertEquals((Date)timestamp1,(Date)timestamp2);
	

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrainimusView Question on Stackoverflow
Solution 1 - JavaDan WattView Answer on Stackoverflow
Solution 2 - JavaEskoView Answer on Stackoverflow
Solution 3 - JavaJoachim SauerView Answer on Stackoverflow
Solution 4 - JavaSethView Answer on Stackoverflow
Solution 5 - JavaGabriel BelingueresView Answer on Stackoverflow
Solution 6 - JavaOgnjen StanićView Answer on Stackoverflow
Solution 7 - JavaMichael EasterView Answer on Stackoverflow
Solution 8 - JavadeamonView Answer on Stackoverflow
Solution 9 - JavaOphidianView Answer on Stackoverflow
Solution 10 - JavaTorbjörn ÖsterdahlView Answer on Stackoverflow
Solution 11 - JavayslView Answer on Stackoverflow
Solution 12 - JavaOliver HernandezView Answer on Stackoverflow
Solution 13 - JavakdombeckView Answer on Stackoverflow
Solution 14 - Javaw25rView Answer on Stackoverflow
Solution 15 - JavaBino ManjasserilView Answer on Stackoverflow
Solution 16 - JavatimomeinenView Answer on Stackoverflow
Solution 17 - JavaRobertoView Answer on Stackoverflow
Solution 18 - JavaFredBoutinView Answer on Stackoverflow
Solution 19 - JavaabasarView Answer on Stackoverflow
Solution 20 - JavansvView Answer on Stackoverflow
Solution 21 - JavaGrubhartView Answer on Stackoverflow