Compare Date objects with different levels of precision

前端 未结 19 2061
日久生厌
日久生厌 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:12

    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.

提交回复
热议问题