比较具有不同精度级别的Date对象 [英] Compare Date objects with different levels of precision
本文介绍了比较具有不同精度级别的Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JUnit测试失败,因为毫秒不同.在这种情况下,我不在乎毫秒.如何更改断言的精度以忽略毫秒(或我希望将其设置为任何精度)?
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)?
我想通过的断言示例:
Date dateOne = new Date();
dateOne.setTime(61202516585000L);
Date dateTwo = new Date();
dateTwo.setTime(61202516585123L);
assertEquals(dateOne, dateTwo);
推荐答案
使用 DateFormat
对象,其格式仅显示您要匹配的部分,并对结果的字符串进行assertEquals()
.您还可以轻松地将其包装在自己的assertDatesAlmostEqual()
方法中.
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.
这篇关于比较具有不同精度级别的Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文