2

I have a client written in Flutter and a server written in Spring Boot. The client sends the DateTime object in the format of yyyy-MM-dd HH:mm:ss.SS. The milliseconds part can change from ".SS" to ".SSSS", sometimes to ".SSS". So there is no stable format for the milliseconds part. The server accepts LocalDateTime object. How can I reconcile both sides with one DateTime format? Actually, I want the server accepts all kind of DateTime objects without looking at the milliseconds part because I don't need the milliseconds part. The accuracy of the DateTime should be up to seconds. What kind of logic should I follow?

I think the best place to handle the format is in the server side dtos. I have found an annotation that accepts the given DateTime parameter.

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss"). However, If the client sends the DateTime in the format of "yyyy-MM-dd HH:mm:ss.SSS" or other than the given format inside the annotation. Java throws the following error.

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2023-05-30 11:08:32.832509": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2023-05-30 11:08:32.832509' could not be parsed, unparsed text found at index 23; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2023-05-30 11:08:32.832509": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2023-05-30 11:08:32.832509' could not be parsed, unparsed text found at index 23<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 320] (through reference chain: com.napsam.wo.dtos.EventCreateRequest["startingTime"])]

What kind of logic should I follow?

Demir
  • 799
  • 3
  • 16
  • It would be easiest if you can just remove the millisecond part from the client. If that's not an option, you can keep a collection of acceptable formats and iterate over it, until one matches. – Chaosfire May 30 '23 at 08:20
  • 2
    Actually, custom `LocalDateTime` deserializer, using internally [this solution for variable length of second fraction](https://stackoverflow.com/questions/30103167/jsr-310-parsing-seconds-fraction-with-variable-length/30107522#30107522) is probably the most elegant way. – Chaosfire May 30 '23 at 08:28
  • Given your DTO tries to parse a String I would apply a substring for the Datetime string in your DTO that excludes the milliseconds so you could then parse it as a LocalDateTime – Guy_g23 May 30 '23 at 08:29
  • Try `@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss[.SSSSSS]")` – g00se May 30 '23 at 09:38
  • @g00se I tried to use that pattern. However, I still get an error while parsing this date time: 2023-05-31 00:00:00.000' – Demir May 30 '23 at 11:33

0 Answers0