Home > Blockchain >  W/System.err: java.time.format.DateTimeParseException: Text '2019-12-22' could not be pars
W/System.err: java.time.format.DateTimeParseException: Text '2019-12-22' could not be pars

Time:11-26

val timestampAsDateString = "25-10-2021"
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

val date = LocalDate.parse(timestampAsDateString, format)
Log.d("parseTesting","Date : ${date}")

I'm getting the following error at the third line of this example code:

W/System.err: java.time.format.DateTimeParseException:
              Text '2019-12-22' could not be parsed at index 5

CodePudding user response:

You have an input String with the value "25-10-2021" but you are trying to parse it with a DateTimeFormatter that expects

  • the year to be first and of 4 digits, your input has a 2-digit day of month there
  • the 2-digit day of month after the second hyphon, your input has the 4-digit year there
  • a time of day, your input does not have at all

That's why I recommend to correct the pattern by

  • swapping 2-digit day of month and 4-digit year (use u if you don't care for era) and
  • leaving the time of day because it would disturb the parsing, you cannot parse something that is just not there, but you can attach such values after having parsed what was present

Here's an example:

fun main(args: Array<String>) {
    // example input
    val timestampAsDateString = "25-10-2021"
    // define a formatter whose pattern matches the input format
    val inputDtf = DateTimeFormatter.ofPattern("dd-MM-uuuu")
    // then parse the input using the formatter
    val parsedDate = LocalDate.parse(timestampAsDateString, inputDtf)
    // print the toString() fun of LocalDate implicitly (ISO standard)
    println("Just parsed the value $parsedDate")
    // if you need a time of day, you could create a LocalDateTime:
    val dateAndTime = LocalDateTime.of(parsedDate, LocalTime.MIN)
    // define a formatter for the output (a built-in one here)
    val outputDtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME
    // print the datetime using the formatter
    println("Added the minimum time of day possible, now it's ${dateAndTime.format(outputDtf)}")
}

This piece of code outputs:

Just parsed the value 2021-10-25
Added the minimum time of day possible, now it's 2021-10-25T00:00:00

CodePudding user response:

A LocalDate can't be formated as a Date Time. So you first need a LocalDateTime.

You can do something like this.

val timestampAsDateString = "25-10-2021"
val dateFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy")
val dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

val date = LocalDate.parse(timestampAsDateString, dateFormat)
LocalDateTime(date, LocalTime.MIN).format(dateTimeFormat)

  • Related