Compare Date objects with different levels of precision

前端 未结 19 2004
日久生厌
日久生厌 2020-12-08 13:01

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 i

19条回答
  •  隐瞒了意图╮
    2020-12-08 13:29

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

提交回复
热议问题