Home > Software design >  Compare Dates in Kotlin
Compare Dates in Kotlin

Time:10-17

How can i compare Dates in Kotlin? I have the Date of an Event as a String (Format:dd/mm/yy) and I want to check if it is within the next 7 Days of the current Date. The time in this case is not relevant or if needet I would use midnight. Can someone please help me with this?

In my current code i got both Dates by this:

val date = document.data["Date"].toString()    //Example: 22/08/22 (dd/MM/yy)
val today = SimpleDateFormat("dd/MM/yy").format(Date()).toString()

this is within a Android environment. I can't get the date more specific because i am getting it from a Database.

CodePudding user response:

  1. Parse string into LocalDate using its parse method. There’s no out-of-the-box DateTimeFormatter for dd/mm/yy format, but you can trivially create one using DateTimeFormatter.ofPattern.
  2. Get current date using LocalDate.now().
  3. diff = ChronoUnit.DAYS.between(now, date1)
  • Related