androidkotlindatesimpledateformatdatetime-parsing

Parse string date to millis in kotlin


I am using SDF to parse a string date to millis with below code

private fun dateToMilliseconds(dateValue: String): Long? {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
val date: Date
try {
    date = sdf.parse(dateValue)!!
    return date.time
} catch (e: Exception) {
    e.printStackTrace()
}
return null
}

And the date is val pdt = "2024-01-17T20:14:29.819Z"

On running it in android I get the exception for unparseable date

java.text.ParseException: Unparseable date: "2024-01-17T20"

Solution

  • I used your code in IntellijIdea and Android Studio and it works properly. Make sure you imported below classes and not using other same name classes:

    import java.text.SimpleDateFormat
    import java.util.*