MaaAn13
MaaAn13

Reputation: 258

Converting string to date fails with exception - unparsable date even though format is correct

Error:

W/System.err: java.text.ParseException: Unparseable date: "Jul 20 2020 17:21:02"

Code:

fun getDate(): Long {
    var dateInMillis = 0L
    var date: Date? = null

    try {
        val stringDate = "Jul 20 2020 17:21:02"
        date = SimpleDateFormat("MMM dd yyyy HH:mm:ss").parse(stringDate)
    } catch (e: Exception) {
        e.printStackTrace()
    }

    date?.let {
        dateInMillis = it.time
    }

    return dateInMillis
}

Format looks correct, but I still get Unparseable date error. Any ideas?

Upvotes: 1

Views: 80

Answers (2)

cangokceaslan
cangokceaslan

Reputation: 482

You can use the code down below.

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

fun main() {
    val str =  "Jul 20 2020 17:21:02";
    val formatter = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss");
    val dt = LocalDateTime.parse(str,formatter);

    println(dt.toString())
}

Upvotes: 0

Ben Shmuel
Ben Shmuel

Reputation: 1989

You should use Locale with SimpleDateFormat, since you are not it creates with the default.

for example:

SimpleDateFormat("MMM dd yyyy HH:mm:ss",Locale.US).parse(stringDate)

Upvotes: 1

Related Questions