This article explores different ways to compare two dates in Kotlin.

1. Using compareTo() function

The standard solution to compare two Date objects is by using the compareTo() function. It returns a value

  1. = 0, if both dates are equal.
  2. < 0, if date is before the specified date.
  3. > 0, if date is after the specified date.

The following program demonstrates it:

Download Code

Output:

12/24/2018 is after 10/10/2017

 
You can also use the compareTo() function for comparing LocalDate, LocalTime, and LocalDateTime objects.

Download Code

Output:

12/24/2018 is after 10/10/2017

2. Using before(), after(), and equals() function

Alternatively, you can also use the before(), after() and equals() from Date class, which returns a boolean value based on the comparison result.

  1. after() returns true if the date is after the specified date.
  2. before() returns true if the date is before the specified date.
  3. equals() returns true if both dates are equal.

The following example demonstrates the usage of these methods to compare two LocalDate:

Download Code

Output:

12/24/2018 is after 10/10/2017

3. Using isBefore(), isAfter(), isEqual() functions

To compare LocalDate, LocalTime, or LocalDateTime objects, you can use the isBefore(), isAfter(), isEqual() functions. The following example demonstrates the usage of these methods to compare two LocalDate:

Download Code

Output:

12/24/2018 is after 10/10/2017

That’s all about comparing two dates in Kotlin.