Search code examples
javadatedatetimekotlinsimpledateformat

Kotlin Unparseable date - ParseException error


I'm seeing the following error when trying to parse a date string, can anyone point me in the right direction to parse this date string?

"2019-01-22T12:43:01Z"

Error:

java.text.ParseException: Unparseable date: "2019-01-22T12:43:01Z"

Code:

package ch02.ex1_1_HelloWorld

import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.Date
import java.util.concurrent.TimeUnit

const val SERVER_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss:SS'Z'" 
val sdf = SimpleDateFormat(SERVER_TIME_FORMAT, Locale.US)

fun main(args: Array<String>) {
    timeSince("2019-01-22T12:43:01Z")
}

fun timeSince(dateStr: String) {
    var diff : Long = 0
    try {
        diff = sdf.parse(dateStr).time - Date().time      
    } catch (e: Exception) {
        print(e)
    }
    "${TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS)} h ago"
} 

Solution

  • Since your input does not contain milli seconds, you can remove the :SS in the pattern:

    const val SERVER_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'" 
    

    And I would suggest to use java.time package.