1

I have configured my application by setting default timestamp format as yyyy-MM-dd HH:mm:ss z

@Configuration
@EnableWebMvc
public class KukunWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    public MappingJackson2HttpMessageConverter jacksonJsonMessageConverter() {
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        ObjectMapper mapper = new ObjectMapper();
        // Registering Hibernate5Module to support lazy objects
        mapper.registerModule(new Hibernate5Module());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"));
        messageConverter.setObjectMapper(mapper);
        return messageConverter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonJsonMessageConverter());

        super.configureMessageConverters(converters);
    }

}

But I am able to pass date field from request body, its giving 400 Bad Request.

Process Entity field:

@Entity
@Table(name = "process")
public class Process{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "process_id")
    private Long processId;

    @Column(name = "process_name")
    @NotNull
    private String processname;

    @Column(name = "process_date")
    @Temporal(TemporalType.DATE)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date processDate;
    //other fields and setter&getter methods
}

controller method:

@PostMapping
public ResponseEntity<Response> createProcess(
        @RequestBody Process process) throws GenericException {

}

request body:

{
    "processDate":"2019-03-30"
}

How can I pass date value via request body when default timestamp set via configuration ?

Krish
  • 1,804
  • 7
  • 37
  • 65
  • Please take a look on two similar questions: [Problem with timezone in Json response from Spring](https://stackoverflow.com/questions/55380919/problem-with-timezone-in-json-response-from-spring) and [Spring Boot Jackson date and timestamp Format](https://stackoverflow.com/questions/55256567/spring-boot-jackson-date-and-timestamp-format) – Michał Ziober Apr 02 '19 at 09:46

1 Answers1

12

let’s take a look at the @JsonFormat annotation to control the date format on individual classes instead of globally, for the entire application:

    public class Event {
        public String name;

        @JsonFormat
          (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
        public Date eventDate;
}
kumar
  • 497
  • 4
  • 12