Java 如何将Joda DateTime对象与可接受的偏移量(公差)进行比较?
我想知道在Java 如何将Joda DateTime对象与可接受的偏移量(公差)进行比较?,java,date,jodatime,Java,Date,Jodatime,我想知道在JodaTime中是否有标准的API来比较2个DateTime对象与指定的公差? 我正在寻找一个单行程序,最好使用Joda标准API。不适用于像中这样的算术表达式 理想情况下,它应该是这样的: boolean areNearlyEqual = SomeJodaAPIClass.equal(dt1, dt2, maxTolerance); 谢谢 使用以下命令: new Duration(dt1, dt2).isShorterThan(Duration.millis(maxToleran
JodaTime
中是否有标准的API来比较2个DateTime
对象与指定的公差?
我正在寻找一个单行程序,最好使用Joda
标准API。不适用于像中这样的算术表达式
理想情况下,它应该是这样的:
boolean areNearlyEqual = SomeJodaAPIClass.equal(dt1, dt2, maxTolerance);
谢谢 使用以下命令:
new Duration(dt1, dt2).isShorterThan(Duration.millis(maxTolerance))
这篇文章很老了,但我发现接受的解决方案中的行有点长,我发现在现有的解决方案中没有更好的。所以我做了一个小班,把它包装成日期和日期时间:
public class DateTimeUtils
{
public static boolean dateIsCloseToNow(Date dateToCheck,
Duration tolerance)
{
return dateIsCloseToNow(new DateTime(dateToCheck), tolerance);
}
public static boolean dateIsCloseToNow(DateTime dateToCheck,
Duration tolerance)
{
return datesAreClose(dateToCheck, DateTime.now(), tolerance);
}
public static boolean datesAreClose(Date date1,
Date date2,
Duration tolerance)
{
return datesAreClose(new DateTime(date1), new DateTime(date2), tolerance);
}
public static boolean datesAreClose(DateTime date1,
DateTime date2,
Duration tolerance)
{
if (date1.isBefore(date2)) {
return new Duration(date1, date2).isShorterThan(tolerance);
}
return new Duration(date2, date1).isShorterThan(tolerance);
}
所以这一行:
new Duration(date.getTime(), System.currentTimeMillis()).isShorterThan(Duration.standardSeconds(5)
变成:
DateUtils.dateIsCloseToNow(date, Duration.standardSeconds(5))
我发现这在需要验证创建日期的单元测试用例中非常有用。这看起来非常方便。我唯一的批评是关于命名的一个小批评:我将命名从“date…”改为“datetime…”(例如“DateTimesAreeEqual”而不是“datesAreEqual”),只是为了避免与命名错误的
java.util.date
和LocalDate
混淆。我也可能会说‘AreClose’而不是‘AreEqual’,或者说‘IsCloseToNow’而不是‘IsNow’。‘IsClose’可能更清楚。至于约会时间,我不确定。因为这些方法都以Date和DateTime作为参数,所以我认为Date更清晰。但是,该类可以重命名为DateTimeUtils。我会编辑这篇文章。