在application.properties进行以下配置:java
#日期格式化 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 spring.jackson.serialization.write-dates-as-timestamps=false
注:spring
- 第1行设置格式
- 第2行设置时区
- 第3行表示不返回时间戳,若是为 true 返回时间戳,若是这三行同时存在,以第3行为准即返回时间戳
可是,网上不少人照着作了仍是有问题,照样不能格式化,为嘛?
这里你们注意,看看本身的代码有没有由于添加拦截器而建立了一个配置类,该类继承了WebMvcConfigurationSupport
,就是他!之前是用WebMvcConfigurerAdapter
,springboot 2.0
建议使用WebMvcConfigurationSupport
。可是在添加拦截器并继承WebMvcConfigurationSupport
后会覆盖@EnableAutoConfiguration
关于WebMvcAutoConfiguration
的配置!从而致使全部的Date返回都变成时间戳!
能够采用另一种方式,在你继承WebMvcConfigurationSupport
的子类中添加日期转换的beanspringboot
@Configuration public class Configurer extends WebMvcConfigurationSupport{ @Autowired HttpInterceptor httpInterceptor; //定义时间格式转换器 @Bean public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); converter.setObjectMapper(mapper); return converter; } //添加转换器 @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //将咱们定义的时间格式转换器添加到转换器列表中, //这样jackson格式化时候但凡遇到Date类型就会转换成咱们定义的格式 converters.add(jackson2HttpMessageConverter()); } @Override protected void addInterceptors(InterceptorRegistry registry) { // TODO Auto-generated method stub registry.addInterceptor(httpInterceptor).addPathPatterns("/**"); super.addInterceptors(registry); } }
或者能够实现WebMvcConfigurer
接口app
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH") .allowCredentials(true).maxAge(3600); } }
个人博客即将同步至腾讯云+社区,邀请你们一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1jx0g2a8qtn8eide
本文同步分享在 博客“吟风者”(JianShu)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。svg