6

I wonder is there any standard API in JodaTime to compare 2 DateTime objects with specified tolerance? I am looking for a one-liner preferably by using Joda standard API. Not for time-aritmethic expressions like in this post.

Ideally, it would be something like:

boolean areNearlyEqual = SomeJodaAPIClass.equal(dt1, dt2, maxTolerance);

Thanks!

Community
  • 1
  • 1
aviad
  • 8,229
  • 9
  • 50
  • 98

2 Answers2

8

Use this:

new Duration(dt1, dt2).isShorterThan(Duration.millis(maxTolerance))
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
Istvan Devai
  • 3,962
  • 23
  • 21
5

This post is old, but I find the line in the accepted solution a bit long and I found nothing better in what exists. So I did a small class that wraps it for Date and DateTime :

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

so this line :

new Duration(date.getTime(), System.currentTimeMillis()).isShorterThan(Duration.standardSeconds(5)

becomes :

DateUtils.dateIsCloseToNow(date, Duration.standardSeconds(5))

I found that really useful in unit test cases where I needed to validate a creation date.

FredBoutin
  • 392
  • 3
  • 16
  • 2
    That looks quite handy. My only criticism is a small one, about naming: I would change the naming from 'date…' to 'datetime…' (such as 'datetimesAreEqual' rather than 'datesAreEqual'), just to avoid confusion with the mis‑named `java.util.Date` and with `LocalDate`. I might also say 'AreClose' rather than 'AreEqual' and 'IsCloseToNow' rather than 'IsNow'. – Basil Bourque May 14 '16 at 04:14
  • "IsClose" might be clearer indeed. For the DateTime, I'm not sure. Since the methods both take Date and DateTime as parameters, I think Date is clearer. Although, the class could be rename to DateTimeUtils. I'll edit the post. – FredBoutin May 16 '16 at 19:26