1

I'm facing some trouble trying to convert String timestamp to LocalDateTime

I receive this string from database 2018013014364112 and it contains date and time which should be 2018-01-30 14:36:41.12 written in more readable format.

When I try to parse it to LocalDateTime i get an Exception

String timestamp = "2018013014364112"
LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyyMMddHHmmssSS"))

Exception:

java.time.format.DateTimeParseException: Text '2018013014364112' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)

However, if i put space in anywhere in the String and FormatPattern, then I get the expected results

String timestamp = "2018 013014364112"
assert LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy MMddHHmmssSS")).toString() == '2018-01-30T14:36:41.120'

Also when i drop the "SS" from the pattern, I get expected results even without the space in the String

String timestamp = "20180130143641"
assert LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")).toString()
        == '2018-01-30T14:36:41'
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Tuomas Valtonen
  • 488
  • 4
  • 13

0 Answers0