phapha pha
phapha pha

Reputation: 329

Finding days difference between dates in Android Kotlin

So, I already search on google and most of them using Java, there is one using Kotlin and often using different time format than what I used (yyyy-mm-dd HH:mm:ss).
So I tried to code and stuck.
So, here is the code :

import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

fun main(args : Array<String>) {

    // 2019-05-24 14:17:00 | 2019-09-13 14:15:51
    val start = "2019-05-24 14:17:00"
    val end = "2019-09-13 14:15:51"

    daysBetweenDates(start, end)
}


fun daysBetweenDates(start: String, end: String) {
    val mStart = LocalDateTime.parse(start)
    val mEnd = LocalDateTime.parse(end)

    val difference = ChronoUnit.DAYS.between(mStart, mEnd)
    println("START => $mStart")
    println("END => $mEnd")
    println("DIFFERENCE => $difference days")
}

But I got an error :

Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-05-24 14:17:00' could not be parsed at index 10
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at java.time.LocalDateTime.parse(LocalDateTime.java:477)
    at MainKt.daysBetweenDates(main.kt:16)
    at MainKt.main(main.kt:11)

Upvotes: 2

Views: 1951

Answers (1)

P.Juni
P.Juni

Reputation: 2485

You need to format the date using for example DateTimeFormatter, so it would look like this more less:

val format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val mStart = LocalDateTime.parse(start, format) 

It happens when your date string is not ISO format that is required by parse method.

Upvotes: 4

Related Questions