Home > Software engineering >  Date Time formatting in scala error: "text could not be parsed at index 0"
Date Time formatting in scala error: "text could not be parsed at index 0"

Time:09-21

I'm trying to parse a string into a timestamp using java.time.format. I am expected it to be in this format "dd/MM/yyyy HH:mm:ss". Here is my code.

val timeString = "Mon Sep 20 15:57:56 BST 2021"
val formatFinal = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
val startTs = formatFinal.parse(timeString)

However i'm getting this error and I'm not sure why. I'm new to scala/java so may have missed something obvious.

 Text 'Mon Sep 20 15:57:56 BST 2021' could not be parsed at index 0

CodePudding user response:

This works.

import java.time.format.{DateTimeFormatter => DTF}

val timeString = "Mon Sep 20 15:57:56 BST 2021"
val formatFinal = DTF.ofPattern("E LLL dd HH:mm:ss z yyyy")
val startTs = formatFinal.parse(timeString)

//val startTs: java.time.temporal.TemporalAccessor = {InstantSeconds=1632113876},ISO,Pacific/Bougainville resolved to 2021-09-20T15:57:56

I'm not sure that's the result you want, but it parses the timeString.

CodePudding user response:

To parse date from string to LocalDateTime and back to string in different format you need to have 2 formatters, first one to read the date from string and parse it to LocalDateTime and the other one to write LocalDateTime back to string in the format you want.

val timeString = "Mon Sep 20 15:57:56 BST 2021"
val formatSource = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy")
val formatOuput = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
val startTs = LocalDateTime.parse(timeString, format).format(formatFinal)
  • Related