I want to have a simple solution to compare two Instant objects in Java. The comparison rule should be based on the date not time.
public boolean isAfterBasedOnDate(Instant instant, Instant compareTo) {
//TODO
}
For example,
Is there any simple way to do it ?
If you want to compare just the date part without considering time, you need to use DateFormat class to format the date into some format and then compare their String value. Alternatively, you can use joda-time which provides a class LocalDate, which represents a Date without time, similar to Java 8's LocalDate class.
Two Instant objects can be compared using the compareTo() method in the Instant class in Java. This method requires a single parameter i.e. the Instant object to be compared.
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.
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
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")));
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With