Spring MVC date format output using MappingJackson2HttpMessageConverter

1.9k views Asked by At

I have a date DTO:

public class SampleDTO{
    Date date;
    //setter, getter, constructor
}

In Spring MVC, I make it in ModelAttribute and sent:

@ModelAttribute("sample")
public SampleDTO getSample() {
    return new SampleDTO(new Date());
}

However, In web page, it shows in following date format:

Thu Aug 31 00:00:00 CEST 2017

Anyone know how to change the date format?

PS: No any change in front-end, no use JSTL, no use tag. I only want to make some change in MappingJackson2HttpMessageConverter

1

There are 1 answers

0
Maxim Kasyanov On

You can config configure message converters in your configuration file:

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
    }
}