How to compare two Instant based on the date not time

while the accepted answer is correct users reading this question should rethink whether they should be using an instant in cases like this. LocalDate is the appropriate way to store and compare dates for which time is irrelevant. A Truncated instant works but it inherently still implies a timezone which would be irrelevant.


Use the truncatedTo-method on the Instant object to only get the number of days.

public boolean isAfterBasedOnDate(Instant instant, Instant compareTo) {
    return instant.truncatedTo(ChronoUnit.DAYS)
                  .isAfter(compareTo.truncatedTo(ChronoUnit.DAYS));
}

@Test
public void test() {
    Assert.assertFalse(isAfterBasedOnDate(
            Instant.parse("2013-01-03T00:00:00Z"),
            Instant.parse("2013-01-03T15:00:00Z")));

    Assert.assertFalse(isAfterBasedOnDate(
            Instant.parse("2013-01-03T15:00:00Z"),
            Instant.parse("2013-01-03T00:00:00Z")));

    Assert.assertFalse(isAfterBasedOnDate(
            Instant.parse("2013-01-02T15:00:00Z"),
            Instant.parse("2013-01-03T00:00:00Z")));

    Assert.assertTrue(isAfterBasedOnDate(
            Instant.parse("2013-01-04T15:00:00Z"),
            Instant.parse("2013-01-03T00:00:00Z")));
}

Truncate the Instant to the number of days and then compare the truncated values.

  public static void main(String[] args) {
    Instant now = Instant.now();
    System.out.println(now);
    Instant truncated = now.truncatedTo(ChronoUnit.DAYS);
    System.out.println(truncated);
  }
2015-01-07T06:43:30.679Z
2015-01-07T00:00:00Z

Tags:

Java