angus
angus

Reputation: 3320

Deserializer String data time using Jackson

I am trying to deserializer the following date time String '6/18/2021 5:25:57 PM' using annotation like that:

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
@JsonProperty("DateModified") 
private LocalDateTime dateModified;

  {
    "XXXX": "....",
    "XXXX1": "....",
    "DateModified": "6/18/2021 5:25:57 PM",

But getting the following error message:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type 
`java.time.LocalDateTime` from String "6/18/2021 5:25:57 PM": Failed to deserialize 
java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '6/18/2021 5:25:57 PM' could not be parsed at index 0

Any idea what I am missing ?

Thank you

Upvotes: 0

Views: 193

Answers (1)

dariosicily
dariosicily

Reputation: 4547

The problem stands in your "dd-MM-yyyy HH:mm:ss" format for which your "6/18/2021 5:25:57 PM" results invalid so you have to do three changes to it to parse your string date :

  1. change - with /.
  2. you exchanged days with months because 18 is surely a day of the month so your pattern should start with M/dd/yyyy instead of dd-MM-yyyy.
  3. your hours are from 1 to 12 because the presence of PM so you have to use h instead of H for hours and adding the a at the end of your pattern for the AM/PM case.

So one valid pattern for the "6/18/2021 5:25:57 PM" string date is the "M/dd/yyyy h:mm:ss a" pattern, you can check the DateTimeFormatter page for more detailed explanations.

Upvotes: 1

Related Questions