Home > Software engineering >  How to use @DateTimeFormat in springboot in DTO?
How to use @DateTimeFormat in springboot in DTO?

Time:07-12

In my Request DTO when I am trying to use pattern HHmm it's not working but HH:mm works.

public class RequestDTO {

    @DateTimeFormat(pattern = "HHmm")
    private LocalTime companyOfficeHoursStart;

}

Below is my MockMVC test:

String requestPayload = "{\"companyOfficeHoursStart\":\"1920\"}";
        RequestBuilder operation = post("/bookings").content(requestPayload)
                .contentType(MediaType.APPLICATION_JSON_VALUE).accept(MediaType.APPLICATION_JSON_VALUE);

How can we use HHmm format ?

CodePudding user response:

We need to use @JsonFormat instead of @DateTimeFormat

CodePudding user response:

@JsonFormat is a Jackson annotation, with Jackson being used to serialize/deserialize POJOs to/from JSON. @DateTimeFormat is a Spring annotation, which is used for setting the format with which the date is saved to the database.

For your use case, you're trying to serialize/deserialize a POJO, so you need to use @DateTimeFormat.

Please see this thread for more information:

https://stackoverflow.com/questions/37871033/spring-datetimeformat-configuration-for-java-time#:~:text=@JsonFormat is a Jackson annotation,rendered in the JSP view.

  • Related