Compare dates

This example shows how to compare two dates using java, java 8 date time api and joda.

Straight up Java

 
@Test
public void compare_two_dates_java () {
    
    Calendar sinceGraduation = Calendar.getInstance();
    sinceGraduation.set(Calendar.YEAR, 1984);
    sinceGraduation.set(Calendar.MONTH, 6);
    sinceGraduation.set(Calendar.DAY_OF_MONTH, 4);
    
    Calendar today = Calendar.getInstance();
    
    assertTrue(today.after(sinceGraduation));
}

Java 8 Date and Time API

LocalDate.isAfter checks if the date is after the provided date.

@Test
public void compare_two_dates_java8 () {
    
    LocalDate sinceGraduation = LocalDate.of(1984, Month.JUNE, 4);
    LocalDate today = LocalDate.now();

    assertTrue(today.isAfter(sinceGraduation));
}

Joda Time

DateTime.isAfter returns true of the instance is after the instance provided comparing solely by millisecond.

@Test
public void compare_two_dates_with_joda() {

    DateTime sinceGraduation = new DateTime(1984, 6, 4, 0, 0,
            GregorianChronology.getInstance());
    DateTime today = new DateTime(); // current date

    assertTrue(today.isAfter(sinceGraduation));
}

Apache Commons

DateUtils.truncatedCompareTo will compare two calendars up to no more than the specified most significant field. In the case below, it will calculate up to the minute field.

@Test
public void compare_two_Dates_apachecommons() {

    Calendar sinceGraduation = Calendar.getInstance();
    sinceGraduation.set(Calendar.YEAR, 1984);
    sinceGraduation.set(Calendar.MONTH, 6);
    sinceGraduation.set(Calendar.DAY_OF_MONTH, 4);

    Calendar today = Calendar.getInstance();

    int val = DateUtils.truncatedCompareTo(sinceGraduation, today,
            Calendar.MINUTE);

    assertTrue(val <= 0);
}