Joda to the rescue

Today I had to compare to dates to find out, if the are on the same date. Both dates had a DateTime format. So my first thought was to just strip the date part. I looked at the java.util.Date class and found that most of the methods are deprecated.

Sure, you can pass the java.util.Date objects to a java.util.Calendar and sethours, minutes and seconds to zero.

But I was looking for a smarter way to accomplish the goal. Joda-Time provides a quality replacement for the Java date and time classes. Joda-Time has been created to radically change date and time handling in Java. The JDK classes Date and Calendar are very badly designed, have had numerous bugs and have odd performance effects.

Using Joda, comparison of dates is easy as pie. The toDateMidnight() method for example sets the time part to zero.

Now you can do the compare with a simple date1.compareTo(date2) .

 

4 thoughts on “Joda to the rescue

  1. While Joda Time is a great library there is an easier way to accomplish what you are trying to do. Simpy remove the time component by doing a simple modulus calculation. I am not trying to be smart about it but we do this quite a lot at OnTime 🙂 Code could look like so:

    Date d = new Date();
    long lngTime = d.getTime();
    lngTime -= lngTime % TimeUnit.DAYS.toMillis(1);
    Date dNoTime = new Date(lngTime);

    The latter date object creation isn’t actually necessary for the comparison. An utility function could be like so:

    private boolean isSameDay(Date d1, Date d2) {
      long lngTime1 = d1.getTime();
      lngTime1 -= lngTime1 % TimeUnit.DAYS.toMillis(1);

      long lngTime2 = d2.getTime();
      lngTime2 -= lngTime2 % TimeUnit.DAYS.toMillis(1);

      return lngTime1 == lngTime2;
    }

    Hope it helps and it helps remove the dependency on Joda Time if that’s all you’re using it for. 

  2. As a general rule, LocalDate should be preferred to DateMidnight for cases like this. Thats because in some time-zones, midnight does not occur on the date of daylight savings change – ie. time jumps from 00:00 to 01:00 with midnight never occurring. DateMidnight clearly has issues with this. LocalDate does not have a time-zone and so handles it fine.

    Mikkel, your code ignores daylight savings time days that last 23 or 25 hours. More generally, its only really reliable if your default time-zone is UTC. If thats fine in your case, great, but please don’t pretend that the code is equivalent.

  3. The date represented by java.util.Date is always the UTC date and hence daylight savings doesn’t apply. Daylight savings and time zones is what the java.util.Calendar is for why this is a perfectly fine approach. Of course the date objects would come from a daylight savings/time zone aware piece of code in a real piece of code where Locale etc. apply.

Comments are closed.