Mark Vitez
Mark Vitez

Reputation: 21

Time between two dates in kotlin

I have a string as a date formatted yyyy-MM-dd, and I want to compare it with the current date. I'm using Android api24, and I want to be able to tell how much time has passed in a format like the first string.

I have tried with the Calendar class, something like this:

   val firstDate=Calendar.getInstance()
   val dateFormat=SimpleDateFormat("yyyy-MM-dd",Locale.getDefault())
   firstDate.time=dateFormat.parse("2001-06-04")

but I get stuck here, getting the current time as a calendar object.

Upvotes: 0

Views: 309

Answers (1)

Kristy Welsh
Kristy Welsh

Reputation: 8340

You can desugar to get to use the Java 8 datetime features:

Java 8+ APIs available through desugaring

Then it is really simple:

private fun convertFromString(datetime: String): LocalDateTime {
    val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.getDefault())
    return LocalDateTime.parse(datetime, dateTimeFormatter)
}

Upvotes: 1

Related Questions