0

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
2
  • 2
    Ham, do you realize your data do not correspond to the pattern you are using? Commented Sep 20, 2021 at 15:13
  • 1
    should i be using val formatFinal = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy") instead? Commented Sep 20, 2021 at 15:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

1 Comment

Since the source string contains time zone information (though ambiguous), I would see if I could correctly parse into a ZonedDateTime rather than LocalDateTime not to miss any information. I would also definitely provide a locale for the formatter since the string is in English and we would like the code to work on on-English installations too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.