比较具有不同精度级别的 Date 对象 [英] Compare Date objects with different levels of precision

查看:22
本文介绍了比较具有不同精度级别的 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)?

我想通过的失败断言示例:

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

推荐答案

使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆